home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / lib / python2.6 / decimal.py < prev    next >
Encoding:
Python Source  |  2009-04-18  |  191.9 KB  |  5,527 lines

  1. # Copyright (c) 2004 Python Software Foundation.
  2. # All rights reserved.
  3.  
  4. # Written by Eric Price <eprice at tjhsst.edu>
  5. #    and Facundo Batista <facundo at taniquetil.com.ar>
  6. #    and Raymond Hettinger <python at rcn.com>
  7. #    and Aahz <aahz at pobox.com>
  8. #    and Tim Peters
  9.  
  10. # This module is currently Py2.3 compatible and should be kept that way
  11. # unless a major compelling advantage arises.  IOW, 2.3 compatibility is
  12. # strongly preferred, but not guaranteed.
  13.  
  14. # Also, this module should be kept in sync with the latest updates of
  15. # the IBM specification as it evolves.  Those updates will be treated
  16. # as bug fixes (deviation from the spec is a compatibility, usability
  17. # bug) and will be backported.  At this point the spec is stabilizing
  18. # and the updates are becoming fewer, smaller, and less significant.
  19.  
  20. """
  21. This is a Py2.3 implementation of decimal floating point arithmetic based on
  22. the General Decimal Arithmetic Specification:
  23.  
  24.     www2.hursley.ibm.com/decimal/decarith.html
  25.  
  26. and IEEE standard 854-1987:
  27.  
  28.     www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
  29.  
  30. Decimal floating point has finite precision with arbitrarily large bounds.
  31.  
  32. The purpose of this module is to support arithmetic using familiar
  33. "schoolhouse" rules and to avoid some of the tricky representation
  34. issues associated with binary floating point.  The package is especially
  35. useful for financial applications or for contexts where users have
  36. expectations that are at odds with binary floating point (for instance,
  37. in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
  38. of the expected Decimal('0.00') returned by decimal floating point).
  39.  
  40. Here are some examples of using the decimal module:
  41.  
  42. >>> from decimal import *
  43. >>> setcontext(ExtendedContext)
  44. >>> Decimal(0)
  45. Decimal('0')
  46. >>> Decimal('1')
  47. Decimal('1')
  48. >>> Decimal('-.0123')
  49. Decimal('-0.0123')
  50. >>> Decimal(123456)
  51. Decimal('123456')
  52. >>> Decimal('123.45e12345678901234567890')
  53. Decimal('1.2345E+12345678901234567892')
  54. >>> Decimal('1.33') + Decimal('1.27')
  55. Decimal('2.60')
  56. >>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
  57. Decimal('-2.20')
  58. >>> dig = Decimal(1)
  59. >>> print dig / Decimal(3)
  60. 0.333333333
  61. >>> getcontext().prec = 18
  62. >>> print dig / Decimal(3)
  63. 0.333333333333333333
  64. >>> print dig.sqrt()
  65. 1
  66. >>> print Decimal(3).sqrt()
  67. 1.73205080756887729
  68. >>> print Decimal(3) ** 123
  69. 4.85192780976896427E+58
  70. >>> inf = Decimal(1) / Decimal(0)
  71. >>> print inf
  72. Infinity
  73. >>> neginf = Decimal(-1) / Decimal(0)
  74. >>> print neginf
  75. -Infinity
  76. >>> print neginf + inf
  77. NaN
  78. >>> print neginf * inf
  79. -Infinity
  80. >>> print dig / 0
  81. Infinity
  82. >>> getcontext().traps[DivisionByZero] = 1
  83. >>> print dig / 0
  84. Traceback (most recent call last):
  85.   ...
  86.   ...
  87.   ...
  88. DivisionByZero: x / 0
  89. >>> c = Context()
  90. >>> c.traps[InvalidOperation] = 0
  91. >>> print c.flags[InvalidOperation]
  92. 0
  93. >>> c.divide(Decimal(0), Decimal(0))
  94. Decimal('NaN')
  95. >>> c.traps[InvalidOperation] = 1
  96. >>> print c.flags[InvalidOperation]
  97. 1
  98. >>> c.flags[InvalidOperation] = 0
  99. >>> print c.flags[InvalidOperation]
  100. 0
  101. >>> print c.divide(Decimal(0), Decimal(0))
  102. Traceback (most recent call last):
  103.   ...
  104.   ...
  105.   ...
  106. InvalidOperation: 0 / 0
  107. >>> print c.flags[InvalidOperation]
  108. 1
  109. >>> c.flags[InvalidOperation] = 0
  110. >>> c.traps[InvalidOperation] = 0
  111. >>> print c.divide(Decimal(0), Decimal(0))
  112. NaN
  113. >>> print c.flags[InvalidOperation]
  114. 1
  115. >>>
  116. """
  117.  
  118. __all__ = [
  119.     # Two major classes
  120.     'Decimal', 'Context',
  121.  
  122.     # Contexts
  123.     'DefaultContext', 'BasicContext', 'ExtendedContext',
  124.  
  125.     # Exceptions
  126.     'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
  127.     'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
  128.  
  129.     # Constants for use in setting up contexts
  130.     'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
  131.     'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
  132.  
  133.     # Functions for manipulating contexts
  134.     'setcontext', 'getcontext', 'localcontext'
  135. ]
  136.  
  137. import copy as _copy
  138. import numbers as _numbers
  139.  
  140. try:
  141.     from collections import namedtuple as _namedtuple
  142.     DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
  143. except ImportError:
  144.     DecimalTuple = lambda *args: args
  145.  
  146. # Rounding
  147. ROUND_DOWN = 'ROUND_DOWN'
  148. ROUND_HALF_UP = 'ROUND_HALF_UP'
  149. ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
  150. ROUND_CEILING = 'ROUND_CEILING'
  151. ROUND_FLOOR = 'ROUND_FLOOR'
  152. ROUND_UP = 'ROUND_UP'
  153. ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
  154. ROUND_05UP = 'ROUND_05UP'
  155.  
  156. # Errors
  157.  
  158. class DecimalException(ArithmeticError):
  159.     """Base exception class.
  160.  
  161.     Used exceptions derive from this.
  162.     If an exception derives from another exception besides this (such as
  163.     Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
  164.     called if the others are present.  This isn't actually used for
  165.     anything, though.
  166.  
  167.     handle  -- Called when context._raise_error is called and the
  168.                trap_enabler is set.  First argument is self, second is the
  169.                context.  More arguments can be given, those being after
  170.                the explanation in _raise_error (For example,
  171.                context._raise_error(NewError, '(-x)!', self._sign) would
  172.                call NewError().handle(context, self._sign).)
  173.  
  174.     To define a new exception, it should be sufficient to have it derive
  175.     from DecimalException.
  176.     """
  177.     def handle(self, context, *args):
  178.         pass
  179.  
  180.  
  181. class Clamped(DecimalException):
  182.     """Exponent of a 0 changed to fit bounds.
  183.  
  184.     This occurs and signals clamped if the exponent of a result has been
  185.     altered in order to fit the constraints of a specific concrete
  186.     representation.  This may occur when the exponent of a zero result would
  187.     be outside the bounds of a representation, or when a large normal
  188.     number would have an encoded exponent that cannot be represented.  In
  189.     this latter case, the exponent is reduced to fit and the corresponding
  190.     number of zero digits are appended to the coefficient ("fold-down").
  191.     """
  192.  
  193. class InvalidOperation(DecimalException):
  194.     """An invalid operation was performed.
  195.  
  196.     Various bad things cause this:
  197.  
  198.     Something creates a signaling NaN
  199.     -INF + INF
  200.     0 * (+-)INF
  201.     (+-)INF / (+-)INF
  202.     x % 0
  203.     (+-)INF % x
  204.     x._rescale( non-integer )
  205.     sqrt(-x) , x > 0
  206.     0 ** 0
  207.     x ** (non-integer)
  208.     x ** (+-)INF
  209.     An operand is invalid
  210.  
  211.     The result of the operation after these is a quiet positive NaN,
  212.     except when the cause is a signaling NaN, in which case the result is
  213.     also a quiet NaN, but with the original sign, and an optional
  214.     diagnostic information.
  215.     """
  216.     def handle(self, context, *args):
  217.         if args:
  218.             ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
  219.             return ans._fix_nan(context)
  220.         return _NaN
  221.  
  222. class ConversionSyntax(InvalidOperation):
  223.     """Trying to convert badly formed string.
  224.  
  225.     This occurs and signals invalid-operation if an string is being
  226.     converted to a number and it does not conform to the numeric string
  227.     syntax.  The result is [0,qNaN].
  228.     """
  229.     def handle(self, context, *args):
  230.         return _NaN
  231.  
  232. class DivisionByZero(DecimalException, ZeroDivisionError):
  233.     """Division by 0.
  234.  
  235.     This occurs and signals division-by-zero if division of a finite number
  236.     by zero was attempted (during a divide-integer or divide operation, or a
  237.     power operation with negative right-hand operand), and the dividend was
  238.     not zero.
  239.  
  240.     The result of the operation is [sign,inf], where sign is the exclusive
  241.     or of the signs of the operands for divide, or is 1 for an odd power of
  242.     -0, for power.
  243.     """
  244.  
  245.     def handle(self, context, sign, *args):
  246.         return _SignedInfinity[sign]
  247.  
  248. class DivisionImpossible(InvalidOperation):
  249.     """Cannot perform the division adequately.
  250.  
  251.     This occurs and signals invalid-operation if the integer result of a
  252.     divide-integer or remainder operation had too many digits (would be
  253.     longer than precision).  The result is [0,qNaN].
  254.     """
  255.  
  256.     def handle(self, context, *args):
  257.         return _NaN
  258.  
  259. class DivisionUndefined(InvalidOperation, ZeroDivisionError):
  260.     """Undefined result of division.
  261.  
  262.     This occurs and signals invalid-operation if division by zero was
  263.     attempted (during a divide-integer, divide, or remainder operation), and
  264.     the dividend is also zero.  The result is [0,qNaN].
  265.     """
  266.  
  267.     def handle(self, context, *args):
  268.         return _NaN
  269.  
  270. class Inexact(DecimalException):
  271.     """Had to round, losing information.
  272.  
  273.     This occurs and signals inexact whenever the result of an operation is
  274.     not exact (that is, it needed to be rounded and any discarded digits
  275.     were non-zero), or if an overflow or underflow condition occurs.  The
  276.     result in all cases is unchanged.
  277.  
  278.     The inexact signal may be tested (or trapped) to determine if a given
  279.     operation (or sequence of operations) was inexact.
  280.     """
  281.  
  282. class InvalidContext(InvalidOperation):
  283.     """Invalid context.  Unknown rounding, for example.
  284.  
  285.     This occurs and signals invalid-operation if an invalid context was
  286.     detected during an operation.  This can occur if contexts are not checked
  287.     on creation and either the precision exceeds the capability of the
  288.     underlying concrete representation or an unknown or unsupported rounding
  289.     was specified.  These aspects of the context need only be checked when
  290.     the values are required to be used.  The result is [0,qNaN].
  291.     """
  292.  
  293.     def handle(self, context, *args):
  294.         return _NaN
  295.  
  296. class Rounded(DecimalException):
  297.     """Number got rounded (not  necessarily changed during rounding).
  298.  
  299.     This occurs and signals rounded whenever the result of an operation is
  300.     rounded (that is, some zero or non-zero digits were discarded from the
  301.     coefficient), or if an overflow or underflow condition occurs.  The
  302.     result in all cases is unchanged.
  303.  
  304.     The rounded signal may be tested (or trapped) to determine if a given
  305.     operation (or sequence of operations) caused a loss of precision.
  306.     """
  307.  
  308. class Subnormal(DecimalException):
  309.     """Exponent < Emin before rounding.
  310.  
  311.     This occurs and signals subnormal whenever the result of a conversion or
  312.     operation is subnormal (that is, its adjusted exponent is less than
  313.     Emin, before any rounding).  The result in all cases is unchanged.
  314.  
  315.     The subnormal signal may be tested (or trapped) to determine if a given
  316.     or operation (or sequence of operations) yielded a subnormal result.
  317.     """
  318.  
  319. class Overflow(Inexact, Rounded):
  320.     """Numerical overflow.
  321.  
  322.     This occurs and signals overflow if the adjusted exponent of a result
  323.     (from a conversion or from an operation that is not an attempt to divide
  324.     by zero), after rounding, would be greater than the largest value that
  325.     can be handled by the implementation (the value Emax).
  326.  
  327.     The result depends on the rounding mode:
  328.  
  329.     For round-half-up and round-half-even (and for round-half-down and
  330.     round-up, if implemented), the result of the operation is [sign,inf],
  331.     where sign is the sign of the intermediate result.  For round-down, the
  332.     result is the largest finite number that can be represented in the
  333.     current precision, with the sign of the intermediate result.  For
  334.     round-ceiling, the result is the same as for round-down if the sign of
  335.     the intermediate result is 1, or is [0,inf] otherwise.  For round-floor,
  336.     the result is the same as for round-down if the sign of the intermediate
  337.     result is 0, or is [1,inf] otherwise.  In all cases, Inexact and Rounded
  338.     will also be raised.
  339.     """
  340.  
  341.     def handle(self, context, sign, *args):
  342.         if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
  343.                                 ROUND_HALF_DOWN, ROUND_UP):
  344.             return _SignedInfinity[sign]
  345.         if sign == 0:
  346.             if context.rounding == ROUND_CEILING:
  347.                 return _SignedInfinity[sign]
  348.             return _dec_from_triple(sign, '9'*context.prec,
  349.                             context.Emax-context.prec+1)
  350.         if sign == 1:
  351.             if context.rounding == ROUND_FLOOR:
  352.                 return _SignedInfinity[sign]
  353.             return _dec_from_triple(sign, '9'*context.prec,
  354.                              context.Emax-context.prec+1)
  355.  
  356.  
  357. class Underflow(Inexact, Rounded, Subnormal):
  358.     """Numerical underflow with result rounded to 0.
  359.  
  360.     This occurs and signals underflow if a result is inexact and the
  361.     adjusted exponent of the result would be smaller (more negative) than
  362.     the smallest value that can be handled by the implementation (the value
  363.     Emin).  That is, the result is both inexact and subnormal.
  364.  
  365.     The result after an underflow will be a subnormal number rounded, if
  366.     necessary, so that its exponent is not less than Etiny.  This may result
  367.     in 0 with the sign of the intermediate result and an exponent of Etiny.
  368.  
  369.     In all cases, Inexact, Rounded, and Subnormal will also be raised.
  370.     """
  371.  
  372. # List of public traps and flags
  373. _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
  374.            Underflow, InvalidOperation, Subnormal]
  375.  
  376. # Map conditions (per the spec) to signals
  377. _condition_map = {ConversionSyntax:InvalidOperation,
  378.                   DivisionImpossible:InvalidOperation,
  379.                   DivisionUndefined:InvalidOperation,
  380.                   InvalidContext:InvalidOperation}
  381.  
  382. ##### Context Functions ##################################################
  383.  
  384. # The getcontext() and setcontext() function manage access to a thread-local
  385. # current context.  Py2.4 offers direct support for thread locals.  If that
  386. # is not available, use threading.currentThread() which is slower but will
  387. # work for older Pythons.  If threads are not part of the build, create a
  388. # mock threading object with threading.local() returning the module namespace.
  389.  
  390. try:
  391.     import threading
  392. except ImportError:
  393.     # Python was compiled without threads; create a mock object instead
  394.     import sys
  395.     class MockThreading(object):
  396.         def local(self, sys=sys):
  397.             return sys.modules[__name__]
  398.     threading = MockThreading()
  399.     del sys, MockThreading
  400.  
  401. try:
  402.     threading.local
  403.  
  404. except AttributeError:
  405.  
  406.     # To fix reloading, force it to create a new context
  407.     # Old contexts have different exceptions in their dicts, making problems.
  408.     if hasattr(threading.currentThread(), '__decimal_context__'):
  409.         del threading.currentThread().__decimal_context__
  410.  
  411.     def setcontext(context):
  412.         """Set this thread's context to context."""
  413.         if context in (DefaultContext, BasicContext, ExtendedContext):
  414.             context = context.copy()
  415.             context.clear_flags()
  416.         threading.currentThread().__decimal_context__ = context
  417.  
  418.     def getcontext():
  419.         """Returns this thread's context.
  420.  
  421.         If this thread does not yet have a context, returns
  422.         a new context and sets this thread's context.
  423.         New contexts are copies of DefaultContext.
  424.         """
  425.         try:
  426.             return threading.currentThread().__decimal_context__
  427.         except AttributeError:
  428.             context = Context()
  429.             threading.currentThread().__decimal_context__ = context
  430.             return context
  431.  
  432. else:
  433.  
  434.     local = threading.local()
  435.     if hasattr(local, '__decimal_context__'):
  436.         del local.__decimal_context__
  437.  
  438.     def getcontext(_local=local):
  439.         """Returns this thread's context.
  440.  
  441.         If this thread does not yet have a context, returns
  442.         a new context and sets this thread's context.
  443.         New contexts are copies of DefaultContext.
  444.         """
  445.         try:
  446.             return _local.__decimal_context__
  447.         except AttributeError:
  448.             context = Context()
  449.             _local.__decimal_context__ = context
  450.             return context
  451.  
  452.     def setcontext(context, _local=local):
  453.         """Set this thread's context to context."""
  454.         if context in (DefaultContext, BasicContext, ExtendedContext):
  455.             context = context.copy()
  456.             context.clear_flags()
  457.         _local.__decimal_context__ = context
  458.  
  459.     del threading, local        # Don't contaminate the namespace
  460.  
  461. def localcontext(ctx=None):
  462.     """Return a context manager for a copy of the supplied context
  463.  
  464.     Uses a copy of the current context if no context is specified
  465.     The returned context manager creates a local decimal context
  466.     in a with statement:
  467.         def sin(x):
  468.              with localcontext() as ctx:
  469.                  ctx.prec += 2
  470.                  # Rest of sin calculation algorithm
  471.                  # uses a precision 2 greater than normal
  472.              return +s  # Convert result to normal precision
  473.  
  474.          def sin(x):
  475.              with localcontext(ExtendedContext):
  476.                  # Rest of sin calculation algorithm
  477.                  # uses the Extended Context from the
  478.                  # General Decimal Arithmetic Specification
  479.              return +s  # Convert result to normal context
  480.  
  481.     >>> setcontext(DefaultContext)
  482.     >>> print getcontext().prec
  483.     28
  484.     >>> with localcontext():
  485.     ...     ctx = getcontext()
  486.     ...     ctx.prec += 2
  487.     ...     print ctx.prec
  488.     ...
  489.     30
  490.     >>> with localcontext(ExtendedContext):
  491.     ...     print getcontext().prec
  492.     ...
  493.     9
  494.     >>> print getcontext().prec
  495.     28
  496.     """
  497.     if ctx is None: ctx = getcontext()
  498.     return _ContextManager(ctx)
  499.  
  500.  
  501. ##### Decimal class #######################################################
  502.  
  503. class Decimal(object):
  504.     """Floating point class for decimal arithmetic."""
  505.  
  506.     __slots__ = ('_exp','_int','_sign', '_is_special')
  507.     # Generally, the value of the Decimal instance is given by
  508.     #  (-1)**_sign * _int * 10**_exp
  509.     # Special values are signified by _is_special == True
  510.  
  511.     # We're immutable, so use __new__ not __init__
  512.     def __new__(cls, value="0", context=None):
  513.         """Create a decimal point instance.
  514.  
  515.         >>> Decimal('3.14')              # string input
  516.         Decimal('3.14')
  517.         >>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent)
  518.         Decimal('3.14')
  519.         >>> Decimal(314)                 # int or long
  520.         Decimal('314')
  521.         >>> Decimal(Decimal(314))        # another decimal instance
  522.         Decimal('314')
  523.         >>> Decimal('  3.14  \\n')        # leading and trailing whitespace okay
  524.         Decimal('3.14')
  525.         """
  526.  
  527.         # Note that the coefficient, self._int, is actually stored as
  528.         # a string rather than as a tuple of digits.  This speeds up
  529.         # the "digits to integer" and "integer to digits" conversions
  530.         # that are used in almost every arithmetic operation on
  531.         # Decimals.  This is an internal detail: the as_tuple function
  532.         # and the Decimal constructor still deal with tuples of
  533.         # digits.
  534.  
  535.         self = object.__new__(cls)
  536.  
  537.         # From a string
  538.         # REs insist on real strings, so we can too.
  539.         if isinstance(value, basestring):
  540.             m = _parser(value.strip())
  541.             if m is None:
  542.                 if context is None:
  543.                     context = getcontext()
  544.                 return context._raise_error(ConversionSyntax,
  545.                                 "Invalid literal for Decimal: %r" % value)
  546.  
  547.             if m.group('sign') == "-":
  548.                 self._sign = 1
  549.             else:
  550.                 self._sign = 0
  551.             intpart = m.group('int')
  552.             if intpart is not None:
  553.                 # finite number
  554.                 fracpart = m.group('frac')
  555.                 exp = int(m.group('exp') or '0')
  556.                 if fracpart is not None:
  557.                     self._int = str((intpart+fracpart).lstrip('0') or '0')
  558.                     self._exp = exp - len(fracpart)
  559.                 else:
  560.                     self._int = str(intpart.lstrip('0') or '0')
  561.                     self._exp = exp
  562.                 self._is_special = False
  563.             else:
  564.                 diag = m.group('diag')
  565.                 if diag is not None:
  566.                     # NaN
  567.                     self._int = str(diag.lstrip('0'))
  568.                     if m.group('signal'):
  569.                         self._exp = 'N'
  570.                     else:
  571.                         self._exp = 'n'
  572.                 else:
  573.                     # infinity
  574.                     self._int = '0'
  575.                     self._exp = 'F'
  576.                 self._is_special = True
  577.             return self
  578.  
  579.         # From an integer
  580.         if isinstance(value, (int,long)):
  581.             if value >= 0:
  582.                 self._sign = 0
  583.             else:
  584.                 self._sign = 1
  585.             self._exp = 0
  586.             self._int = str(abs(value))
  587.             self._is_special = False
  588.             return self
  589.  
  590.         # From another decimal
  591.         if isinstance(value, Decimal):
  592.             self._exp  = value._exp
  593.             self._sign = value._sign
  594.             self._int  = value._int
  595.             self._is_special  = value._is_special
  596.             return self
  597.  
  598.         # From an internal working value
  599.         if isinstance(value, _WorkRep):
  600.             self._sign = value.sign
  601.             self._int = str(value.int)
  602.             self._exp = int(value.exp)
  603.             self._is_special = False
  604.             return self
  605.  
  606.         # tuple/list conversion (possibly from as_tuple())
  607.         if isinstance(value, (list,tuple)):
  608.             if len(value) != 3:
  609.                 raise ValueError('Invalid tuple size in creation of Decimal '
  610.                                  'from list or tuple.  The list or tuple '
  611.                                  'should have exactly three elements.')
  612.             # process sign.  The isinstance test rejects floats
  613.             if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
  614.                 raise ValueError("Invalid sign.  The first value in the tuple "
  615.                                  "should be an integer; either 0 for a "
  616.                                  "positive number or 1 for a negative number.")
  617.             self._sign = value[0]
  618.             if value[2] == 'F':
  619.                 # infinity: value[1] is ignored
  620.                 self._int = '0'
  621.                 self._exp = value[2]
  622.                 self._is_special = True
  623.             else:
  624.                 # process and validate the digits in value[1]
  625.                 digits = []
  626.                 for digit in value[1]:
  627.                     if isinstance(digit, (int, long)) and 0 <= digit <= 9:
  628.                         # skip leading zeros
  629.                         if digits or digit != 0:
  630.                             digits.append(digit)
  631.                     else:
  632.                         raise ValueError("The second value in the tuple must "
  633.                                          "be composed of integers in the range "
  634.                                          "0 through 9.")
  635.                 if value[2] in ('n', 'N'):
  636.                     # NaN: digits form the diagnostic
  637.                     self._int = ''.join(map(str, digits))
  638.                     self._exp = value[2]
  639.                     self._is_special = True
  640.                 elif isinstance(value[2], (int, long)):
  641.                     # finite number: digits give the coefficient
  642.                     self._int = ''.join(map(str, digits or [0]))
  643.                     self._exp = value[2]
  644.                     self._is_special = False
  645.                 else:
  646.                     raise ValueError("The third value in the tuple must "
  647.                                      "be an integer, or one of the "
  648.                                      "strings 'F', 'n', 'N'.")
  649.             return self
  650.  
  651.         if isinstance(value, float):
  652.             raise TypeError("Cannot convert float to Decimal.  " +
  653.                             "First convert the float to a string")
  654.  
  655.         raise TypeError("Cannot convert %r to Decimal" % value)
  656.  
  657.     def _isnan(self):
  658.         """Returns whether the number is not actually one.
  659.  
  660.         0 if a number
  661.         1 if NaN
  662.         2 if sNaN
  663.         """
  664.         if self._is_special:
  665.             exp = self._exp
  666.             if exp == 'n':
  667.                 return 1
  668.             elif exp == 'N':
  669.                 return 2
  670.         return 0
  671.  
  672.     def _isinfinity(self):
  673.         """Returns whether the number is infinite
  674.  
  675.         0 if finite or not a number
  676.         1 if +INF
  677.         -1 if -INF
  678.         """
  679.         if self._exp == 'F':
  680.             if self._sign:
  681.                 return -1
  682.             return 1
  683.         return 0
  684.  
  685.     def _check_nans(self, other=None, context=None):
  686.         """Returns whether the number is not actually one.
  687.  
  688.         if self, other are sNaN, signal
  689.         if self, other are NaN return nan
  690.         return 0
  691.  
  692.         Done before operations.
  693.         """
  694.  
  695.         self_is_nan = self._isnan()
  696.         if other is None:
  697.             other_is_nan = False
  698.         else:
  699.             other_is_nan = other._isnan()
  700.  
  701.         if self_is_nan or other_is_nan:
  702.             if context is None:
  703.                 context = getcontext()
  704.  
  705.             if self_is_nan == 2:
  706.                 return context._raise_error(InvalidOperation, 'sNaN',
  707.                                         self)
  708.             if other_is_nan == 2:
  709.                 return context._raise_error(InvalidOperation, 'sNaN',
  710.                                         other)
  711.             if self_is_nan:
  712.                 return self._fix_nan(context)
  713.  
  714.             return other._fix_nan(context)
  715.         return 0
  716.  
  717.     def _compare_check_nans(self, other, context):
  718.         """Version of _check_nans used for the signaling comparisons
  719.         compare_signal, __le__, __lt__, __ge__, __gt__.
  720.  
  721.         Signal InvalidOperation if either self or other is a (quiet
  722.         or signaling) NaN.  Signaling NaNs take precedence over quiet
  723.         NaNs.
  724.  
  725.         Return 0 if neither operand is a NaN.
  726.  
  727.         """
  728.         if context is None:
  729.             context = getcontext()
  730.  
  731.         if self._is_special or other._is_special:
  732.             if self.is_snan():
  733.                 return context._raise_error(InvalidOperation,
  734.                                             'comparison involving sNaN',
  735.                                             self)
  736.             elif other.is_snan():
  737.                 return context._raise_error(InvalidOperation,
  738.                                             'comparison involving sNaN',
  739.                                             other)
  740.             elif self.is_qnan():
  741.                 return context._raise_error(InvalidOperation,
  742.                                             'comparison involving NaN',
  743.                                             self)
  744.             elif other.is_qnan():
  745.                 return context._raise_error(InvalidOperation,
  746.                                             'comparison involving NaN',
  747.                                             other)
  748.         return 0
  749.  
  750.     def __nonzero__(self):
  751.         """Return True if self is nonzero; otherwise return False.
  752.  
  753.         NaNs and infinities are considered nonzero.
  754.         """
  755.         return self._is_special or self._int != '0'
  756.  
  757.     def _cmp(self, other):
  758.         """Compare the two non-NaN decimal instances self and other.
  759.  
  760.         Returns -1 if self < other, 0 if self == other and 1
  761.         if self > other.  This routine is for internal use only."""
  762.  
  763.         if self._is_special or other._is_special:
  764.             self_inf = self._isinfinity()
  765.             other_inf = other._isinfinity()
  766.             if self_inf == other_inf:
  767.                 return 0
  768.             elif self_inf < other_inf:
  769.                 return -1
  770.             else:
  771.                 return 1
  772.  
  773.         # check for zeros;  Decimal('0') == Decimal('-0')
  774.         if not self:
  775.             if not other:
  776.                 return 0
  777.             else:
  778.                 return -((-1)**other._sign)
  779.         if not other:
  780.             return (-1)**self._sign
  781.  
  782.         # If different signs, neg one is less
  783.         if other._sign < self._sign:
  784.             return -1
  785.         if self._sign < other._sign:
  786.             return 1
  787.  
  788.         self_adjusted = self.adjusted()
  789.         other_adjusted = other.adjusted()
  790.         if self_adjusted == other_adjusted:
  791.             self_padded = self._int + '0'*(self._exp - other._exp)
  792.             other_padded = other._int + '0'*(other._exp - self._exp)
  793.             if self_padded == other_padded:
  794.                 return 0
  795.             elif self_padded < other_padded:
  796.                 return -(-1)**self._sign
  797.             else:
  798.                 return (-1)**self._sign
  799.         elif self_adjusted > other_adjusted:
  800.             return (-1)**self._sign
  801.         else: # self_adjusted < other_adjusted
  802.             return -((-1)**self._sign)
  803.  
  804.     # Note: The Decimal standard doesn't cover rich comparisons for
  805.     # Decimals.  In particular, the specification is silent on the
  806.     # subject of what should happen for a comparison involving a NaN.
  807.     # We take the following approach:
  808.     #
  809.     #   == comparisons involving a NaN always return False
  810.     #   != comparisons involving a NaN always return True
  811.     #   <, >, <= and >= comparisons involving a (quiet or signaling)
  812.     #      NaN signal InvalidOperation, and return False if the
  813.     #      InvalidOperation is not trapped.
  814.     #
  815.     # This behavior is designed to conform as closely as possible to
  816.     # that specified by IEEE 754.
  817.  
  818.     def __eq__(self, other):
  819.         other = _convert_other(other)
  820.         if other is NotImplemented:
  821.             return other
  822.         if self.is_nan() or other.is_nan():
  823.             return False
  824.         return self._cmp(other) == 0
  825.  
  826.     def __ne__(self, other):
  827.         other = _convert_other(other)
  828.         if other is NotImplemented:
  829.             return other
  830.         if self.is_nan() or other.is_nan():
  831.             return True
  832.         return self._cmp(other) != 0
  833.  
  834.     def __lt__(self, other, context=None):
  835.         other = _convert_other(other)
  836.         if other is NotImplemented:
  837.             return other
  838.         ans = self._compare_check_nans(other, context)
  839.         if ans:
  840.             return False
  841.         return self._cmp(other) < 0
  842.  
  843.     def __le__(self, other, context=None):
  844.         other = _convert_other(other)
  845.         if other is NotImplemented:
  846.             return other
  847.         ans = self._compare_check_nans(other, context)
  848.         if ans:
  849.             return False
  850.         return self._cmp(other) <= 0
  851.  
  852.     def __gt__(self, other, context=None):
  853.         other = _convert_other(other)
  854.         if other is NotImplemented:
  855.             return other
  856.         ans = self._compare_check_nans(other, context)
  857.         if ans:
  858.             return False
  859.         return self._cmp(other) > 0
  860.  
  861.     def __ge__(self, other, context=None):
  862.         other = _convert_other(other)
  863.         if other is NotImplemented:
  864.             return other
  865.         ans = self._compare_check_nans(other, context)
  866.         if ans:
  867.             return False
  868.         return self._cmp(other) >= 0
  869.  
  870.     def compare(self, other, context=None):
  871.         """Compares one to another.
  872.  
  873.         -1 => a < b
  874.         0  => a = b
  875.         1  => a > b
  876.         NaN => one is NaN
  877.         Like __cmp__, but returns Decimal instances.
  878.         """
  879.         other = _convert_other(other, raiseit=True)
  880.  
  881.         # Compare(NaN, NaN) = NaN
  882.         if (self._is_special or other and other._is_special):
  883.             ans = self._check_nans(other, context)
  884.             if ans:
  885.                 return ans
  886.  
  887.         return Decimal(self._cmp(other))
  888.  
  889.     def __hash__(self):
  890.         """x.__hash__() <==> hash(x)"""
  891.         # Decimal integers must hash the same as the ints
  892.         #
  893.         # The hash of a nonspecial noninteger Decimal must depend only
  894.         # on the value of that Decimal, and not on its representation.
  895.         # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
  896.         if self._is_special:
  897.             if self._isnan():
  898.                 raise TypeError('Cannot hash a NaN value.')
  899.             return hash(str(self))
  900.         if not self:
  901.             return 0
  902.         if self._isinteger():
  903.             op = _WorkRep(self.to_integral_value())
  904.             # to make computation feasible for Decimals with large
  905.             # exponent, we use the fact that hash(n) == hash(m) for
  906.             # any two nonzero integers n and m such that (i) n and m
  907.             # have the same sign, and (ii) n is congruent to m modulo
  908.             # 2**64-1.  So we can replace hash((-1)**s*c*10**e) with
  909.             # hash((-1)**s*c*pow(10, e, 2**64-1).
  910.             return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
  911.         # The value of a nonzero nonspecial Decimal instance is
  912.         # faithfully represented by the triple consisting of its sign,
  913.         # its adjusted exponent, and its coefficient with trailing
  914.         # zeros removed.
  915.         return hash((self._sign,
  916.                      self._exp+len(self._int),
  917.                      self._int.rstrip('0')))
  918.  
  919.     def as_tuple(self):
  920.         """Represents the number as a triple tuple.
  921.  
  922.         To show the internals exactly as they are.
  923.         """
  924.         return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
  925.  
  926.     def __repr__(self):
  927.         """Represents the number as an instance of Decimal."""
  928.         # Invariant:  eval(repr(d)) == d
  929.         return "Decimal('%s')" % str(self)
  930.  
  931.     def __str__(self, eng=False, context=None):
  932.         """Return string representation of the number in scientific notation.
  933.  
  934.         Captures all of the information in the underlying representation.
  935.         """
  936.  
  937.         sign = ['', '-'][self._sign]
  938.         if self._is_special:
  939.             if self._exp == 'F':
  940.                 return sign + 'Infinity'
  941.             elif self._exp == 'n':
  942.                 return sign + 'NaN' + self._int
  943.             else: # self._exp == 'N'
  944.                 return sign + 'sNaN' + self._int
  945.  
  946.         # number of digits of self._int to left of decimal point
  947.         leftdigits = self._exp + len(self._int)
  948.  
  949.         # dotplace is number of digits of self._int to the left of the
  950.         # decimal point in the mantissa of the output string (that is,
  951.         # after adjusting the exponent)
  952.         if self._exp <= 0 and leftdigits > -6:
  953.             # no exponent required
  954.             dotplace = leftdigits
  955.         elif not eng:
  956.             # usual scientific notation: 1 digit on left of the point
  957.             dotplace = 1
  958.         elif self._int == '0':
  959.             # engineering notation, zero
  960.             dotplace = (leftdigits + 1) % 3 - 1
  961.         else:
  962.             # engineering notation, nonzero
  963.             dotplace = (leftdigits - 1) % 3 + 1
  964.  
  965.         if dotplace <= 0:
  966.             intpart = '0'
  967.             fracpart = '.' + '0'*(-dotplace) + self._int
  968.         elif dotplace >= len(self._int):
  969.             intpart = self._int+'0'*(dotplace-len(self._int))
  970.             fracpart = ''
  971.         else:
  972.             intpart = self._int[:dotplace]
  973.             fracpart = '.' + self._int[dotplace:]
  974.         if leftdigits == dotplace:
  975.             exp = ''
  976.         else:
  977.             if context is None:
  978.                 context = getcontext()
  979.             exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
  980.  
  981.         return sign + intpart + fracpart + exp
  982.  
  983.     def to_eng_string(self, context=None):
  984.         """Convert to engineering-type string.
  985.  
  986.         Engineering notation has an exponent which is a multiple of 3, so there
  987.         are up to 3 digits left of the decimal place.
  988.  
  989.         Same rules for when in exponential and when as a value as in __str__.
  990.         """
  991.         return self.__str__(eng=True, context=context)
  992.  
  993.     def __neg__(self, context=None):
  994.         """Returns a copy with the sign switched.
  995.  
  996.         Rounds, if it has reason.
  997.         """
  998.         if self._is_special:
  999.             ans = self._check_nans(context=context)
  1000.             if ans:
  1001.                 return ans
  1002.  
  1003.         if not self:
  1004.             # -Decimal('0') is Decimal('0'), not Decimal('-0')
  1005.             ans = self.copy_abs()
  1006.         else:
  1007.             ans = self.copy_negate()
  1008.  
  1009.         if context is None:
  1010.             context = getcontext()
  1011.         return ans._fix(context)
  1012.  
  1013.     def __pos__(self, context=None):
  1014.         """Returns a copy, unless it is a sNaN.
  1015.  
  1016.         Rounds the number (if more then precision digits)
  1017.         """
  1018.         if self._is_special:
  1019.             ans = self._check_nans(context=context)
  1020.             if ans:
  1021.                 return ans
  1022.  
  1023.         if not self:
  1024.             # + (-0) = 0
  1025.             ans = self.copy_abs()
  1026.         else:
  1027.             ans = Decimal(self)
  1028.  
  1029.         if context is None:
  1030.             context = getcontext()
  1031.         return ans._fix(context)
  1032.  
  1033.     def __abs__(self, round=True, context=None):
  1034.         """Returns the absolute value of self.
  1035.  
  1036.         If the keyword argument 'round' is false, do not round.  The
  1037.         expression self.__abs__(round=False) is equivalent to
  1038.         self.copy_abs().
  1039.         """
  1040.         if not round:
  1041.             return self.copy_abs()
  1042.  
  1043.         if self._is_special:
  1044.             ans = self._check_nans(context=context)
  1045.             if ans:
  1046.                 return ans
  1047.  
  1048.         if self._sign:
  1049.             ans = self.__neg__(context=context)
  1050.         else:
  1051.             ans = self.__pos__(context=context)
  1052.  
  1053.         return ans
  1054.  
  1055.     def __add__(self, other, context=None):
  1056.         """Returns self + other.
  1057.  
  1058.         -INF + INF (or the reverse) cause InvalidOperation errors.
  1059.         """
  1060.         other = _convert_other(other)
  1061.         if other is NotImplemented:
  1062.             return other
  1063.  
  1064.         if context is None:
  1065.             context = getcontext()
  1066.  
  1067.         if self._is_special or other._is_special:
  1068.             ans = self._check_nans(other, context)
  1069.             if ans:
  1070.                 return ans
  1071.  
  1072.             if self._isinfinity():
  1073.                 # If both INF, same sign => same as both, opposite => error.
  1074.                 if self._sign != other._sign and other._isinfinity():
  1075.                     return context._raise_error(InvalidOperation, '-INF + INF')
  1076.                 return Decimal(self)
  1077.             if other._isinfinity():
  1078.                 return Decimal(other)  # Can't both be infinity here
  1079.  
  1080.         exp = min(self._exp, other._exp)
  1081.         negativezero = 0
  1082.         if context.rounding == ROUND_FLOOR and self._sign != other._sign:
  1083.             # If the answer is 0, the sign should be negative, in this case.
  1084.             negativezero = 1
  1085.  
  1086.         if not self and not other:
  1087.             sign = min(self._sign, other._sign)
  1088.             if negativezero:
  1089.                 sign = 1
  1090.             ans = _dec_from_triple(sign, '0', exp)
  1091.             ans = ans._fix(context)
  1092.             return ans
  1093.         if not self:
  1094.             exp = max(exp, other._exp - context.prec-1)
  1095.             ans = other._rescale(exp, context.rounding)
  1096.             ans = ans._fix(context)
  1097.             return ans
  1098.         if not other:
  1099.             exp = max(exp, self._exp - context.prec-1)
  1100.             ans = self._rescale(exp, context.rounding)
  1101.             ans = ans._fix(context)
  1102.             return ans
  1103.  
  1104.         op1 = _WorkRep(self)
  1105.         op2 = _WorkRep(other)
  1106.         op1, op2 = _normalize(op1, op2, context.prec)
  1107.  
  1108.         result = _WorkRep()
  1109.         if op1.sign != op2.sign:
  1110.             # Equal and opposite
  1111.             if op1.int == op2.int:
  1112.                 ans = _dec_from_triple(negativezero, '0', exp)
  1113.                 ans = ans._fix(context)
  1114.                 return ans
  1115.             if op1.int < op2.int:
  1116.                 op1, op2 = op2, op1
  1117.                 # OK, now abs(op1) > abs(op2)
  1118.             if op1.sign == 1:
  1119.                 result.sign = 1
  1120.                 op1.sign, op2.sign = op2.sign, op1.sign
  1121.             else:
  1122.                 result.sign = 0
  1123.                 # So we know the sign, and op1 > 0.
  1124.         elif op1.sign == 1:
  1125.             result.sign = 1
  1126.             op1.sign, op2.sign = (0, 0)
  1127.         else:
  1128.             result.sign = 0
  1129.         # Now, op1 > abs(op2) > 0
  1130.  
  1131.         if op2.sign == 0:
  1132.             result.int = op1.int + op2.int
  1133.         else:
  1134.             result.int = op1.int - op2.int
  1135.  
  1136.         result.exp = op1.exp
  1137.         ans = Decimal(result)
  1138.         ans = ans._fix(context)
  1139.         return ans
  1140.  
  1141.     __radd__ = __add__
  1142.  
  1143.     def __sub__(self, other, context=None):
  1144.         """Return self - other"""
  1145.         other = _convert_other(other)
  1146.         if other is NotImplemented:
  1147.             return other
  1148.  
  1149.         if self._is_special or other._is_special:
  1150.             ans = self._check_nans(other, context=context)
  1151.             if ans:
  1152.                 return ans
  1153.  
  1154.         # self - other is computed as self + other.copy_negate()
  1155.         return self.__add__(other.copy_negate(), context=context)
  1156.  
  1157.     def __rsub__(self, other, context=None):
  1158.         """Return other - self"""
  1159.         other = _convert_other(other)
  1160.         if other is NotImplemented:
  1161.             return other
  1162.  
  1163.         return other.__sub__(self, context=context)
  1164.  
  1165.     def __mul__(self, other, context=None):
  1166.         """Return self * other.
  1167.  
  1168.         (+-) INF * 0 (or its reverse) raise InvalidOperation.
  1169.         """
  1170.         other = _convert_other(other)
  1171.         if other is NotImplemented:
  1172.             return other
  1173.  
  1174.         if context is None:
  1175.             context = getcontext()
  1176.  
  1177.         resultsign = self._sign ^ other._sign
  1178.  
  1179.         if self._is_special or other._is_special:
  1180.             ans = self._check_nans(other, context)
  1181.             if ans:
  1182.                 return ans
  1183.  
  1184.             if self._isinfinity():
  1185.                 if not other:
  1186.                     return context._raise_error(InvalidOperation, '(+-)INF * 0')
  1187.                 return _SignedInfinity[resultsign]
  1188.  
  1189.             if other._isinfinity():
  1190.                 if not self:
  1191.                     return context._raise_error(InvalidOperation, '0 * (+-)INF')
  1192.                 return _SignedInfinity[resultsign]
  1193.  
  1194.         resultexp = self._exp + other._exp
  1195.  
  1196.         # Special case for multiplying by zero
  1197.         if not self or not other:
  1198.             ans = _dec_from_triple(resultsign, '0', resultexp)
  1199.             # Fixing in case the exponent is out of bounds
  1200.             ans = ans._fix(context)
  1201.             return ans
  1202.  
  1203.         # Special case for multiplying by power of 10
  1204.         if self._int == '1':
  1205.             ans = _dec_from_triple(resultsign, other._int, resultexp)
  1206.             ans = ans._fix(context)
  1207.             return ans
  1208.         if other._int == '1':
  1209.             ans = _dec_from_triple(resultsign, self._int, resultexp)
  1210.             ans = ans._fix(context)
  1211.             return ans
  1212.  
  1213.         op1 = _WorkRep(self)
  1214.         op2 = _WorkRep(other)
  1215.  
  1216.         ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
  1217.         ans = ans._fix(context)
  1218.  
  1219.         return ans
  1220.     __rmul__ = __mul__
  1221.  
  1222.     def __truediv__(self, other, context=None):
  1223.         """Return self / other."""
  1224.         other = _convert_other(other)
  1225.         if other is NotImplemented:
  1226.             return NotImplemented
  1227.  
  1228.         if context is None:
  1229.             context = getcontext()
  1230.  
  1231.         sign = self._sign ^ other._sign
  1232.  
  1233.         if self._is_special or other._is_special:
  1234.             ans = self._check_nans(other, context)
  1235.             if ans:
  1236.                 return ans
  1237.  
  1238.             if self._isinfinity() and other._isinfinity():
  1239.                 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
  1240.  
  1241.             if self._isinfinity():
  1242.                 return _SignedInfinity[sign]
  1243.  
  1244.             if other._isinfinity():
  1245.                 context._raise_error(Clamped, 'Division by infinity')
  1246.                 return _dec_from_triple(sign, '0', context.Etiny())
  1247.  
  1248.         # Special cases for zeroes
  1249.         if not other:
  1250.             if not self:
  1251.                 return context._raise_error(DivisionUndefined, '0 / 0')
  1252.             return context._raise_error(DivisionByZero, 'x / 0', sign)
  1253.  
  1254.         if not self:
  1255.             exp = self._exp - other._exp
  1256.             coeff = 0
  1257.         else:
  1258.             # OK, so neither = 0, INF or NaN
  1259.             shift = len(other._int) - len(self._int) + context.prec + 1
  1260.             exp = self._exp - other._exp - shift
  1261.             op1 = _WorkRep(self)
  1262.             op2 = _WorkRep(other)
  1263.             if shift >= 0:
  1264.                 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
  1265.             else:
  1266.                 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
  1267.             if remainder:
  1268.                 # result is not exact; adjust to ensure correct rounding
  1269.                 if coeff % 5 == 0:
  1270.                     coeff += 1
  1271.             else:
  1272.                 # result is exact; get as close to ideal exponent as possible
  1273.                 ideal_exp = self._exp - other._exp
  1274.                 while exp < ideal_exp and coeff % 10 == 0:
  1275.                     coeff //= 10
  1276.                     exp += 1
  1277.  
  1278.         ans = _dec_from_triple(sign, str(coeff), exp)
  1279.         return ans._fix(context)
  1280.  
  1281.     def _divide(self, other, context):
  1282.         """Return (self // other, self % other), to context.prec precision.
  1283.  
  1284.         Assumes that neither self nor other is a NaN, that self is not
  1285.         infinite and that other is nonzero.
  1286.         """
  1287.         sign = self._sign ^ other._sign
  1288.         if other._isinfinity():
  1289.             ideal_exp = self._exp
  1290.         else:
  1291.             ideal_exp = min(self._exp, other._exp)
  1292.  
  1293.         expdiff = self.adjusted() - other.adjusted()
  1294.         if not self or other._isinfinity() or expdiff <= -2:
  1295.             return (_dec_from_triple(sign, '0', 0),
  1296.                     self._rescale(ideal_exp, context.rounding))
  1297.         if expdiff <= context.prec:
  1298.             op1 = _WorkRep(self)
  1299.             op2 = _WorkRep(other)
  1300.             if op1.exp >= op2.exp:
  1301.                 op1.int *= 10**(op1.exp - op2.exp)
  1302.             else:
  1303.                 op2.int *= 10**(op2.exp - op1.exp)
  1304.             q, r = divmod(op1.int, op2.int)
  1305.             if q < 10**context.prec:
  1306.                 return (_dec_from_triple(sign, str(q), 0),
  1307.                         _dec_from_triple(self._sign, str(r), ideal_exp))
  1308.  
  1309.         # Here the quotient is too large to be representable
  1310.         ans = context._raise_error(DivisionImpossible,
  1311.                                    'quotient too large in //, % or divmod')
  1312.         return ans, ans
  1313.  
  1314.     def __rtruediv__(self, other, context=None):
  1315.         """Swaps self/other and returns __truediv__."""
  1316.         other = _convert_other(other)
  1317.         if other is NotImplemented:
  1318.             return other
  1319.         return other.__truediv__(self, context=context)
  1320.  
  1321.     __div__ = __truediv__
  1322.     __rdiv__ = __rtruediv__
  1323.  
  1324.     def __divmod__(self, other, context=None):
  1325.         """
  1326.         Return (self // other, self % other)
  1327.         """
  1328.         other = _convert_other(other)
  1329.         if other is NotImplemented:
  1330.             return other
  1331.  
  1332.         if context is None:
  1333.             context = getcontext()
  1334.  
  1335.         ans = self._check_nans(other, context)
  1336.         if ans:
  1337.             return (ans, ans)
  1338.  
  1339.         sign = self._sign ^ other._sign
  1340.         if self._isinfinity():
  1341.             if other._isinfinity():
  1342.                 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
  1343.                 return ans, ans
  1344.             else:
  1345.                 return (_SignedInfinity[sign],
  1346.                         context._raise_error(InvalidOperation, 'INF % x'))
  1347.  
  1348.         if not other:
  1349.             if not self:
  1350.                 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
  1351.                 return ans, ans
  1352.             else:
  1353.                 return (context._raise_error(DivisionByZero, 'x // 0', sign),
  1354.                         context._raise_error(InvalidOperation, 'x % 0'))
  1355.  
  1356.         quotient, remainder = self._divide(other, context)
  1357.         remainder = remainder._fix(context)
  1358.         return quotient, remainder
  1359.  
  1360.     def __rdivmod__(self, other, context=None):
  1361.         """Swaps self/other and returns __divmod__."""
  1362.         other = _convert_other(other)
  1363.         if other is NotImplemented:
  1364.             return other
  1365.         return other.__divmod__(self, context=context)
  1366.  
  1367.     def __mod__(self, other, context=None):
  1368.         """
  1369.         self % other
  1370.         """
  1371.         other = _convert_other(other)
  1372.         if other is NotImplemented:
  1373.             return other
  1374.  
  1375.         if context is None:
  1376.             context = getcontext()
  1377.  
  1378.         ans = self._check_nans(other, context)
  1379.         if ans:
  1380.             return ans
  1381.  
  1382.         if self._isinfinity():
  1383.             return context._raise_error(InvalidOperation, 'INF % x')
  1384.         elif not other:
  1385.             if self:
  1386.                 return context._raise_error(InvalidOperation, 'x % 0')
  1387.             else:
  1388.                 return context._raise_error(DivisionUndefined, '0 % 0')
  1389.  
  1390.         remainder = self._divide(other, context)[1]
  1391.         remainder = remainder._fix(context)
  1392.         return remainder
  1393.  
  1394.     def __rmod__(self, other, context=None):
  1395.         """Swaps self/other and returns __mod__."""
  1396.         other = _convert_other(other)
  1397.         if other is NotImplemented:
  1398.             return other
  1399.         return other.__mod__(self, context=context)
  1400.  
  1401.     def remainder_near(self, other, context=None):
  1402.         """
  1403.         Remainder nearest to 0-  abs(remainder-near) <= other/2
  1404.         """
  1405.         if context is None:
  1406.             context = getcontext()
  1407.  
  1408.         other = _convert_other(other, raiseit=True)
  1409.  
  1410.         ans = self._check_nans(other, context)
  1411.         if ans:
  1412.             return ans
  1413.  
  1414.         # self == +/-infinity -> InvalidOperation
  1415.         if self._isinfinity():
  1416.             return context._raise_error(InvalidOperation,
  1417.                                         'remainder_near(infinity, x)')
  1418.  
  1419.         # other == 0 -> either InvalidOperation or DivisionUndefined
  1420.         if not other:
  1421.             if self:
  1422.                 return context._raise_error(InvalidOperation,
  1423.                                             'remainder_near(x, 0)')
  1424.             else:
  1425.                 return context._raise_error(DivisionUndefined,
  1426.                                             'remainder_near(0, 0)')
  1427.  
  1428.         # other = +/-infinity -> remainder = self
  1429.         if other._isinfinity():
  1430.             ans = Decimal(self)
  1431.             return ans._fix(context)
  1432.  
  1433.         # self = 0 -> remainder = self, with ideal exponent
  1434.         ideal_exponent = min(self._exp, other._exp)
  1435.         if not self:
  1436.             ans = _dec_from_triple(self._sign, '0', ideal_exponent)
  1437.             return ans._fix(context)
  1438.  
  1439.         # catch most cases of large or small quotient
  1440.         expdiff = self.adjusted() - other.adjusted()
  1441.         if expdiff >= context.prec + 1:
  1442.             # expdiff >= prec+1 => abs(self/other) > 10**prec
  1443.             return context._raise_error(DivisionImpossible)
  1444.         if expdiff <= -2:
  1445.             # expdiff <= -2 => abs(self/other) < 0.1
  1446.             ans = self._rescale(ideal_exponent, context.rounding)
  1447.             return ans._fix(context)
  1448.  
  1449.         # adjust both arguments to have the same exponent, then divide
  1450.         op1 = _WorkRep(self)
  1451.         op2 = _WorkRep(other)
  1452.         if op1.exp >= op2.exp:
  1453.             op1.int *= 10**(op1.exp - op2.exp)
  1454.         else:
  1455.             op2.int *= 10**(op2.exp - op1.exp)
  1456.         q, r = divmod(op1.int, op2.int)
  1457.         # remainder is r*10**ideal_exponent; other is +/-op2.int *
  1458.         # 10**ideal_exponent.   Apply correction to ensure that
  1459.         # abs(remainder) <= abs(other)/2
  1460.         if 2*r + (q&1) > op2.int:
  1461.             r -= op2.int
  1462.             q += 1
  1463.  
  1464.         if q >= 10**context.prec:
  1465.             return context._raise_error(DivisionImpossible)
  1466.  
  1467.         # result has same sign as self unless r is negative
  1468.         sign = self._sign
  1469.         if r < 0:
  1470.             sign = 1-sign
  1471.             r = -r
  1472.  
  1473.         ans = _dec_from_triple(sign, str(r), ideal_exponent)
  1474.         return ans._fix(context)
  1475.  
  1476.     def __floordiv__(self, other, context=None):
  1477.         """self // other"""
  1478.         other = _convert_other(other)
  1479.         if other is NotImplemented:
  1480.             return other
  1481.  
  1482.         if context is None:
  1483.             context = getcontext()
  1484.  
  1485.         ans = self._check_nans(other, context)
  1486.         if ans:
  1487.             return ans
  1488.  
  1489.         if self._isinfinity():
  1490.             if other._isinfinity():
  1491.                 return context._raise_error(InvalidOperation, 'INF // INF')
  1492.             else:
  1493.                 return _SignedInfinity[self._sign ^ other._sign]
  1494.  
  1495.         if not other:
  1496.             if self:
  1497.                 return context._raise_error(DivisionByZero, 'x // 0',
  1498.                                             self._sign ^ other._sign)
  1499.             else:
  1500.                 return context._raise_error(DivisionUndefined, '0 // 0')
  1501.  
  1502.         return self._divide(other, context)[0]
  1503.  
  1504.     def __rfloordiv__(self, other, context=None):
  1505.         """Swaps self/other and returns __floordiv__."""
  1506.         other = _convert_other(other)
  1507.         if other is NotImplemented:
  1508.             return other
  1509.         return other.__floordiv__(self, context=context)
  1510.  
  1511.     def __float__(self):
  1512.         """Float representation."""
  1513.         return float(str(self))
  1514.  
  1515.     def __int__(self):
  1516.         """Converts self to an int, truncating if necessary."""
  1517.         if self._is_special:
  1518.             if self._isnan():
  1519.                 context = getcontext()
  1520.                 return context._raise_error(InvalidContext)
  1521.             elif self._isinfinity():
  1522.                 raise OverflowError("Cannot convert infinity to int")
  1523.         s = (-1)**self._sign
  1524.         if self._exp >= 0:
  1525.             return s*int(self._int)*10**self._exp
  1526.         else:
  1527.             return s*int(self._int[:self._exp] or '0')
  1528.  
  1529.     __trunc__ = __int__
  1530.  
  1531.     def real(self):
  1532.         return self
  1533.     real = property(real)
  1534.  
  1535.     def imag(self):
  1536.         return Decimal(0)
  1537.     imag = property(imag)
  1538.  
  1539.     def conjugate(self):
  1540.         return self
  1541.  
  1542.     def __complex__(self):
  1543.         return complex(float(self))
  1544.  
  1545.     def __long__(self):
  1546.         """Converts to a long.
  1547.  
  1548.         Equivalent to long(int(self))
  1549.         """
  1550.         return long(self.__int__())
  1551.  
  1552.     def _fix_nan(self, context):
  1553.         """Decapitate the payload of a NaN to fit the context"""
  1554.         payload = self._int
  1555.  
  1556.         # maximum length of payload is precision if _clamp=0,
  1557.         # precision-1 if _clamp=1.
  1558.         max_payload_len = context.prec - context._clamp
  1559.         if len(payload) > max_payload_len:
  1560.             payload = payload[len(payload)-max_payload_len:].lstrip('0')
  1561.             return _dec_from_triple(self._sign, payload, self._exp, True)
  1562.         return Decimal(self)
  1563.  
  1564.     def _fix(self, context):
  1565.         """Round if it is necessary to keep self within prec precision.
  1566.  
  1567.         Rounds and fixes the exponent.  Does not raise on a sNaN.
  1568.  
  1569.         Arguments:
  1570.         self - Decimal instance
  1571.         context - context used.
  1572.         """
  1573.  
  1574.         if self._is_special:
  1575.             if self._isnan():
  1576.                 # decapitate payload if necessary
  1577.                 return self._fix_nan(context)
  1578.             else:
  1579.                 # self is +/-Infinity; return unaltered
  1580.                 return Decimal(self)
  1581.  
  1582.         # if self is zero then exponent should be between Etiny and
  1583.         # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
  1584.         Etiny = context.Etiny()
  1585.         Etop = context.Etop()
  1586.         if not self:
  1587.             exp_max = [context.Emax, Etop][context._clamp]
  1588.             new_exp = min(max(self._exp, Etiny), exp_max)
  1589.             if new_exp != self._exp:
  1590.                 context._raise_error(Clamped)
  1591.                 return _dec_from_triple(self._sign, '0', new_exp)
  1592.             else:
  1593.                 return Decimal(self)
  1594.  
  1595.         # exp_min is the smallest allowable exponent of the result,
  1596.         # equal to max(self.adjusted()-context.prec+1, Etiny)
  1597.         exp_min = len(self._int) + self._exp - context.prec
  1598.         if exp_min > Etop:
  1599.             # overflow: exp_min > Etop iff self.adjusted() > Emax
  1600.             context._raise_error(Inexact)
  1601.             context._raise_error(Rounded)
  1602.             return context._raise_error(Overflow, 'above Emax', self._sign)
  1603.         self_is_subnormal = exp_min < Etiny
  1604.         if self_is_subnormal:
  1605.             context._raise_error(Subnormal)
  1606.             exp_min = Etiny
  1607.  
  1608.         # round if self has too many digits
  1609.         if self._exp < exp_min:
  1610.             context._raise_error(Rounded)
  1611.             digits = len(self._int) + self._exp - exp_min
  1612.             if digits < 0:
  1613.                 self = _dec_from_triple(self._sign, '1', exp_min-1)
  1614.                 digits = 0
  1615.             this_function = getattr(self, self._pick_rounding_function[context.rounding])
  1616.             changed = this_function(digits)
  1617.             coeff = self._int[:digits] or '0'
  1618.             if changed == 1:
  1619.                 coeff = str(int(coeff)+1)
  1620.             ans = _dec_from_triple(self._sign, coeff, exp_min)
  1621.  
  1622.             if changed:
  1623.                 context._raise_error(Inexact)
  1624.                 if self_is_subnormal:
  1625.                     context._raise_error(Underflow)
  1626.                     if not ans:
  1627.                         # raise Clamped on underflow to 0
  1628.                         context._raise_error(Clamped)
  1629.                 elif len(ans._int) == context.prec+1:
  1630.                     # we get here only if rescaling rounds the
  1631.                     # cofficient up to exactly 10**context.prec
  1632.                     if ans._exp < Etop:
  1633.                         ans = _dec_from_triple(ans._sign,
  1634.                                                    ans._int[:-1], ans._exp+1)
  1635.                     else:
  1636.                         # Inexact and Rounded have already been raised
  1637.                         ans = context._raise_error(Overflow, 'above Emax',
  1638.                                                    self._sign)
  1639.             return ans
  1640.  
  1641.         # fold down if _clamp == 1 and self has too few digits
  1642.         if context._clamp == 1 and self._exp > Etop:
  1643.             context._raise_error(Clamped)
  1644.             self_padded = self._int + '0'*(self._exp - Etop)
  1645.             return _dec_from_triple(self._sign, self_padded, Etop)
  1646.  
  1647.         # here self was representable to begin with; return unchanged
  1648.         return Decimal(self)
  1649.  
  1650.     _pick_rounding_function = {}
  1651.  
  1652.     # for each of the rounding functions below:
  1653.     #   self is a finite, nonzero Decimal
  1654.     #   prec is an integer satisfying 0 <= prec < len(self._int)
  1655.     #
  1656.     # each function returns either -1, 0, or 1, as follows:
  1657.     #   1 indicates that self should be rounded up (away from zero)
  1658.     #   0 indicates that self should be truncated, and that all the
  1659.     #     digits to be truncated are zeros (so the value is unchanged)
  1660.     #  -1 indicates that there are nonzero digits to be truncated
  1661.  
  1662.     def _round_down(self, prec):
  1663.         """Also known as round-towards-0, truncate."""
  1664.         if _all_zeros(self._int, prec):
  1665.             return 0
  1666.         else:
  1667.             return -1
  1668.  
  1669.     def _round_up(self, prec):
  1670.         """Rounds away from 0."""
  1671.         return -self._round_down(prec)
  1672.  
  1673.     def _round_half_up(self, prec):
  1674.         """Rounds 5 up (away from 0)"""
  1675.         if self._int[prec] in '56789':
  1676.             return 1
  1677.         elif _all_zeros(self._int, prec):
  1678.             return 0
  1679.         else:
  1680.             return -1
  1681.  
  1682.     def _round_half_down(self, prec):
  1683.         """Round 5 down"""
  1684.         if _exact_half(self._int, prec):
  1685.             return -1
  1686.         else:
  1687.             return self._round_half_up(prec)
  1688.  
  1689.     def _round_half_even(self, prec):
  1690.         """Round 5 to even, rest to nearest."""
  1691.         if _exact_half(self._int, prec) and \
  1692.                 (prec == 0 or self._int[prec-1] in '02468'):
  1693.             return -1
  1694.         else:
  1695.             return self._round_half_up(prec)
  1696.  
  1697.     def _round_ceiling(self, prec):
  1698.         """Rounds up (not away from 0 if negative.)"""
  1699.         if self._sign:
  1700.             return self._round_down(prec)
  1701.         else:
  1702.             return -self._round_down(prec)
  1703.  
  1704.     def _round_floor(self, prec):
  1705.         """Rounds down (not towards 0 if negative)"""
  1706.         if not self._sign:
  1707.             return self._round_down(prec)
  1708.         else:
  1709.             return -self._round_down(prec)
  1710.  
  1711.     def _round_05up(self, prec):
  1712.         """Round down unless digit prec-1 is 0 or 5."""
  1713.         if prec and self._int[prec-1] not in '05':
  1714.             return self._round_down(prec)
  1715.         else:
  1716.             return -self._round_down(prec)
  1717.  
  1718.     def fma(self, other, third, context=None):
  1719.         """Fused multiply-add.
  1720.  
  1721.         Returns self*other+third with no rounding of the intermediate
  1722.         product self*other.
  1723.  
  1724.         self and other are multiplied together, with no rounding of
  1725.         the result.  The third operand is then added to the result,
  1726.         and a single final rounding is performed.
  1727.         """
  1728.  
  1729.         other = _convert_other(other, raiseit=True)
  1730.  
  1731.         # compute product; raise InvalidOperation if either operand is
  1732.         # a signaling NaN or if the product is zero times infinity.
  1733.         if self._is_special or other._is_special:
  1734.             if context is None:
  1735.                 context = getcontext()
  1736.             if self._exp == 'N':
  1737.                 return context._raise_error(InvalidOperation, 'sNaN', self)
  1738.             if other._exp == 'N':
  1739.                 return context._raise_error(InvalidOperation, 'sNaN', other)
  1740.             if self._exp == 'n':
  1741.                 product = self
  1742.             elif other._exp == 'n':
  1743.                 product = other
  1744.             elif self._exp == 'F':
  1745.                 if not other:
  1746.                     return context._raise_error(InvalidOperation,
  1747.                                                 'INF * 0 in fma')
  1748.                 product = _SignedInfinity[self._sign ^ other._sign]
  1749.             elif other._exp == 'F':
  1750.                 if not self:
  1751.                     return context._raise_error(InvalidOperation,
  1752.                                                 '0 * INF in fma')
  1753.                 product = _SignedInfinity[self._sign ^ other._sign]
  1754.         else:
  1755.             product = _dec_from_triple(self._sign ^ other._sign,
  1756.                                        str(int(self._int) * int(other._int)),
  1757.                                        self._exp + other._exp)
  1758.  
  1759.         third = _convert_other(third, raiseit=True)
  1760.         return product.__add__(third, context)
  1761.  
  1762.     def _power_modulo(self, other, modulo, context=None):
  1763.         """Three argument version of __pow__"""
  1764.  
  1765.         # if can't convert other and modulo to Decimal, raise
  1766.         # TypeError; there's no point returning NotImplemented (no
  1767.         # equivalent of __rpow__ for three argument pow)
  1768.         other = _convert_other(other, raiseit=True)
  1769.         modulo = _convert_other(modulo, raiseit=True)
  1770.  
  1771.         if context is None:
  1772.             context = getcontext()
  1773.  
  1774.         # deal with NaNs: if there are any sNaNs then first one wins,
  1775.         # (i.e. behaviour for NaNs is identical to that of fma)
  1776.         self_is_nan = self._isnan()
  1777.         other_is_nan = other._isnan()
  1778.         modulo_is_nan = modulo._isnan()
  1779.         if self_is_nan or other_is_nan or modulo_is_nan:
  1780.             if self_is_nan == 2:
  1781.                 return context._raise_error(InvalidOperation, 'sNaN',
  1782.                                         self)
  1783.             if other_is_nan == 2:
  1784.                 return context._raise_error(InvalidOperation, 'sNaN',
  1785.                                         other)
  1786.             if modulo_is_nan == 2:
  1787.                 return context._raise_error(InvalidOperation, 'sNaN',
  1788.                                         modulo)
  1789.             if self_is_nan:
  1790.                 return self._fix_nan(context)
  1791.             if other_is_nan:
  1792.                 return other._fix_nan(context)
  1793.             return modulo._fix_nan(context)
  1794.  
  1795.         # check inputs: we apply same restrictions as Python's pow()
  1796.         if not (self._isinteger() and
  1797.                 other._isinteger() and
  1798.                 modulo._isinteger()):
  1799.             return context._raise_error(InvalidOperation,
  1800.                                         'pow() 3rd argument not allowed '
  1801.                                         'unless all arguments are integers')
  1802.         if other < 0:
  1803.             return context._raise_error(InvalidOperation,
  1804.                                         'pow() 2nd argument cannot be '
  1805.                                         'negative when 3rd argument specified')
  1806.         if not modulo:
  1807.             return context._raise_error(InvalidOperation,
  1808.                                         'pow() 3rd argument cannot be 0')
  1809.  
  1810.         # additional restriction for decimal: the modulus must be less
  1811.         # than 10**prec in absolute value
  1812.         if modulo.adjusted() >= context.prec:
  1813.             return context._raise_error(InvalidOperation,
  1814.                                         'insufficient precision: pow() 3rd '
  1815.                                         'argument must not have more than '
  1816.                                         'precision digits')
  1817.  
  1818.         # define 0**0 == NaN, for consistency with two-argument pow
  1819.         # (even though it hurts!)
  1820.         if not other and not self:
  1821.             return context._raise_error(InvalidOperation,
  1822.                                         'at least one of pow() 1st argument '
  1823.                                         'and 2nd argument must be nonzero ;'
  1824.                                         '0**0 is not defined')
  1825.  
  1826.         # compute sign of result
  1827.         if other._iseven():
  1828.             sign = 0
  1829.         else:
  1830.             sign = self._sign
  1831.  
  1832.         # convert modulo to a Python integer, and self and other to
  1833.         # Decimal integers (i.e. force their exponents to be >= 0)
  1834.         modulo = abs(int(modulo))
  1835.         base = _WorkRep(self.to_integral_value())
  1836.         exponent = _WorkRep(other.to_integral_value())
  1837.  
  1838.         # compute result using integer pow()
  1839.         base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
  1840.         for i in xrange(exponent.exp):
  1841.             base = pow(base, 10, modulo)
  1842.         base = pow(base, exponent.int, modulo)
  1843.  
  1844.         return _dec_from_triple(sign, str(base), 0)
  1845.  
  1846.     def _power_exact(self, other, p):
  1847.         """Attempt to compute self**other exactly.
  1848.  
  1849.         Given Decimals self and other and an integer p, attempt to
  1850.         compute an exact result for the power self**other, with p
  1851.         digits of precision.  Return None if self**other is not
  1852.         exactly representable in p digits.
  1853.  
  1854.         Assumes that elimination of special cases has already been
  1855.         performed: self and other must both be nonspecial; self must
  1856.         be positive and not numerically equal to 1; other must be
  1857.         nonzero.  For efficiency, other._exp should not be too large,
  1858.         so that 10**abs(other._exp) is a feasible calculation."""
  1859.  
  1860.         # In the comments below, we write x for the value of self and
  1861.         # y for the value of other.  Write x = xc*10**xe and y =
  1862.         # yc*10**ye.
  1863.  
  1864.         # The main purpose of this method is to identify the *failure*
  1865.         # of x**y to be exactly representable with as little effort as
  1866.         # possible.  So we look for cheap and easy tests that
  1867.         # eliminate the possibility of x**y being exact.  Only if all
  1868.         # these tests are passed do we go on to actually compute x**y.
  1869.  
  1870.         # Here's the main idea.  First normalize both x and y.  We
  1871.         # express y as a rational m/n, with m and n relatively prime
  1872.         # and n>0.  Then for x**y to be exactly representable (at
  1873.         # *any* precision), xc must be the nth power of a positive
  1874.         # integer and xe must be divisible by n.  If m is negative
  1875.         # then additionally xc must be a power of either 2 or 5, hence
  1876.         # a power of 2**n or 5**n.
  1877.         #
  1878.         # There's a limit to how small |y| can be: if y=m/n as above
  1879.         # then:
  1880.         #
  1881.         #  (1) if xc != 1 then for the result to be representable we
  1882.         #      need xc**(1/n) >= 2, and hence also xc**|y| >= 2.  So
  1883.         #      if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
  1884.         #      2**(1/|y|), hence xc**|y| < 2 and the result is not
  1885.         #      representable.
  1886.         #
  1887.         #  (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1.  Hence if
  1888.         #      |y| < 1/|xe| then the result is not representable.
  1889.         #
  1890.         # Note that since x is not equal to 1, at least one of (1) and
  1891.         # (2) must apply.  Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
  1892.         # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
  1893.         #
  1894.         # There's also a limit to how large y can be, at least if it's
  1895.         # positive: the normalized result will have coefficient xc**y,
  1896.         # so if it's representable then xc**y < 10**p, and y <
  1897.         # p/log10(xc).  Hence if y*log10(xc) >= p then the result is
  1898.         # not exactly representable.
  1899.  
  1900.         # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
  1901.         # so |y| < 1/xe and the result is not representable.
  1902.         # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
  1903.         # < 1/nbits(xc).
  1904.  
  1905.         x = _WorkRep(self)
  1906.         xc, xe = x.int, x.exp
  1907.         while xc % 10 == 0:
  1908.             xc //= 10
  1909.             xe += 1
  1910.  
  1911.         y = _WorkRep(other)
  1912.         yc, ye = y.int, y.exp
  1913.         while yc % 10 == 0:
  1914.             yc //= 10
  1915.             ye += 1
  1916.  
  1917.         # case where xc == 1: result is 10**(xe*y), with xe*y
  1918.         # required to be an integer
  1919.         if xc == 1:
  1920.             if ye >= 0:
  1921.                 exponent = xe*yc*10**ye
  1922.             else:
  1923.                 exponent, remainder = divmod(xe*yc, 10**-ye)
  1924.                 if remainder:
  1925.                     return None
  1926.             if y.sign == 1:
  1927.                 exponent = -exponent
  1928.             # if other is a nonnegative integer, use ideal exponent
  1929.             if other._isinteger() and other._sign == 0:
  1930.                 ideal_exponent = self._exp*int(other)
  1931.                 zeros = min(exponent-ideal_exponent, p-1)
  1932.             else:
  1933.                 zeros = 0
  1934.             return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
  1935.  
  1936.         # case where y is negative: xc must be either a power
  1937.         # of 2 or a power of 5.
  1938.         if y.sign == 1:
  1939.             last_digit = xc % 10
  1940.             if last_digit in (2,4,6,8):
  1941.                 # quick test for power of 2
  1942.                 if xc & -xc != xc:
  1943.                     return None
  1944.                 # now xc is a power of 2; e is its exponent
  1945.                 e = _nbits(xc)-1
  1946.                 # find e*y and xe*y; both must be integers
  1947.                 if ye >= 0:
  1948.                     y_as_int = yc*10**ye
  1949.                     e = e*y_as_int
  1950.                     xe = xe*y_as_int
  1951.                 else:
  1952.                     ten_pow = 10**-ye
  1953.                     e, remainder = divmod(e*yc, ten_pow)
  1954.                     if remainder:
  1955.                         return None
  1956.                     xe, remainder = divmod(xe*yc, ten_pow)
  1957.                     if remainder:
  1958.                         return None
  1959.  
  1960.                 if e*65 >= p*93: # 93/65 > log(10)/log(5)
  1961.                     return None
  1962.                 xc = 5**e
  1963.  
  1964.             elif last_digit == 5:
  1965.                 # e >= log_5(xc) if xc is a power of 5; we have
  1966.                 # equality all the way up to xc=5**2658
  1967.                 e = _nbits(xc)*28//65
  1968.                 xc, remainder = divmod(5**e, xc)
  1969.                 if remainder:
  1970.                     return None
  1971.                 while xc % 5 == 0:
  1972.                     xc //= 5
  1973.                     e -= 1
  1974.                 if ye >= 0:
  1975.                     y_as_integer = yc*10**ye
  1976.                     e = e*y_as_integer
  1977.                     xe = xe*y_as_integer
  1978.                 else:
  1979.                     ten_pow = 10**-ye
  1980.                     e, remainder = divmod(e*yc, ten_pow)
  1981.                     if remainder:
  1982.                         return None
  1983.                     xe, remainder = divmod(xe*yc, ten_pow)
  1984.                     if remainder:
  1985.                         return None
  1986.                 if e*3 >= p*10: # 10/3 > log(10)/log(2)
  1987.                     return None
  1988.                 xc = 2**e
  1989.             else:
  1990.                 return None
  1991.  
  1992.             if xc >= 10**p:
  1993.                 return None
  1994.             xe = -e-xe
  1995.             return _dec_from_triple(0, str(xc), xe)
  1996.  
  1997.         # now y is positive; find m and n such that y = m/n
  1998.         if ye >= 0:
  1999.             m, n = yc*10**ye, 1
  2000.         else:
  2001.             if xe != 0 and len(str(abs(yc*xe))) <= -ye:
  2002.                 return None
  2003.             xc_bits = _nbits(xc)
  2004.             if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
  2005.                 return None
  2006.             m, n = yc, 10**(-ye)
  2007.             while m % 2 == n % 2 == 0:
  2008.                 m //= 2
  2009.                 n //= 2
  2010.             while m % 5 == n % 5 == 0:
  2011.                 m //= 5
  2012.                 n //= 5
  2013.  
  2014.         # compute nth root of xc*10**xe
  2015.         if n > 1:
  2016.             # if 1 < xc < 2**n then xc isn't an nth power
  2017.             if xc != 1 and xc_bits <= n:
  2018.                 return None
  2019.  
  2020.             xe, rem = divmod(xe, n)
  2021.             if rem != 0:
  2022.                 return None
  2023.  
  2024.             # compute nth root of xc using Newton's method
  2025.             a = 1L << -(-_nbits(xc)//n) # initial estimate
  2026.             while True:
  2027.                 q, r = divmod(xc, a**(n-1))
  2028.                 if a <= q:
  2029.                     break
  2030.                 else:
  2031.                     a = (a*(n-1) + q)//n
  2032.             if not (a == q and r == 0):
  2033.                 return None
  2034.             xc = a
  2035.  
  2036.         # now xc*10**xe is the nth root of the original xc*10**xe
  2037.         # compute mth power of xc*10**xe
  2038.  
  2039.         # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
  2040.         # 10**p and the result is not representable.
  2041.         if xc > 1 and m > p*100//_log10_lb(xc):
  2042.             return None
  2043.         xc = xc**m
  2044.         xe *= m
  2045.         if xc > 10**p:
  2046.             return None
  2047.  
  2048.         # by this point the result *is* exactly representable
  2049.         # adjust the exponent to get as close as possible to the ideal
  2050.         # exponent, if necessary
  2051.         str_xc = str(xc)
  2052.         if other._isinteger() and other._sign == 0:
  2053.             ideal_exponent = self._exp*int(other)
  2054.             zeros = min(xe-ideal_exponent, p-len(str_xc))
  2055.         else:
  2056.             zeros = 0
  2057.         return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
  2058.  
  2059.     def __pow__(self, other, modulo=None, context=None):
  2060.         """Return self ** other [ % modulo].
  2061.  
  2062.         With two arguments, compute self**other.
  2063.  
  2064.         With three arguments, compute (self**other) % modulo.  For the
  2065.         three argument form, the following restrictions on the
  2066.         arguments hold:
  2067.  
  2068.          - all three arguments must be integral
  2069.          - other must be nonnegative
  2070.          - either self or other (or both) must be nonzero
  2071.          - modulo must be nonzero and must have at most p digits,
  2072.            where p is the context precision.
  2073.  
  2074.         If any of these restrictions is violated the InvalidOperation
  2075.         flag is raised.
  2076.  
  2077.         The result of pow(self, other, modulo) is identical to the
  2078.         result that would be obtained by computing (self**other) %
  2079.         modulo with unbounded precision, but is computed more
  2080.         efficiently.  It is always exact.
  2081.         """
  2082.  
  2083.         if modulo is not None:
  2084.             return self._power_modulo(other, modulo, context)
  2085.  
  2086.         other = _convert_other(other)
  2087.         if other is NotImplemented:
  2088.             return other
  2089.  
  2090.         if context is None:
  2091.             context = getcontext()
  2092.  
  2093.         # either argument is a NaN => result is NaN
  2094.         ans = self._check_nans(other, context)
  2095.         if ans:
  2096.             return ans
  2097.  
  2098.         # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
  2099.         if not other:
  2100.             if not self:
  2101.                 return context._raise_error(InvalidOperation, '0 ** 0')
  2102.             else:
  2103.                 return _One
  2104.  
  2105.         # result has sign 1 iff self._sign is 1 and other is an odd integer
  2106.         result_sign = 0
  2107.         if self._sign == 1:
  2108.             if other._isinteger():
  2109.                 if not other._iseven():
  2110.                     result_sign = 1
  2111.             else:
  2112.                 # -ve**noninteger = NaN
  2113.                 # (-0)**noninteger = 0**noninteger
  2114.                 if self:
  2115.                     return context._raise_error(InvalidOperation,
  2116.                         'x ** y with x negative and y not an integer')
  2117.             # negate self, without doing any unwanted rounding
  2118.             self = self.copy_negate()
  2119.  
  2120.         # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
  2121.         if not self:
  2122.             if other._sign == 0:
  2123.                 return _dec_from_triple(result_sign, '0', 0)
  2124.             else:
  2125.                 return _SignedInfinity[result_sign]
  2126.  
  2127.         # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
  2128.         if self._isinfinity():
  2129.             if other._sign == 0:
  2130.                 return _SignedInfinity[result_sign]
  2131.             else:
  2132.                 return _dec_from_triple(result_sign, '0', 0)
  2133.  
  2134.         # 1**other = 1, but the choice of exponent and the flags
  2135.         # depend on the exponent of self, and on whether other is a
  2136.         # positive integer, a negative integer, or neither
  2137.         if self == _One:
  2138.             if other._isinteger():
  2139.                 # exp = max(self._exp*max(int(other), 0),
  2140.                 # 1-context.prec) but evaluating int(other) directly
  2141.                 # is dangerous until we know other is small (other
  2142.                 # could be 1e999999999)
  2143.                 if other._sign == 1:
  2144.                     multiplier = 0
  2145.                 elif other > context.prec:
  2146.                     multiplier = context.prec
  2147.                 else:
  2148.                     multiplier = int(other)
  2149.  
  2150.                 exp = self._exp * multiplier
  2151.                 if exp < 1-context.prec:
  2152.                     exp = 1-context.prec
  2153.                     context._raise_error(Rounded)
  2154.             else:
  2155.                 context._raise_error(Inexact)
  2156.                 context._raise_error(Rounded)
  2157.                 exp = 1-context.prec
  2158.  
  2159.             return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
  2160.  
  2161.         # compute adjusted exponent of self
  2162.         self_adj = self.adjusted()
  2163.  
  2164.         # self ** infinity is infinity if self > 1, 0 if self < 1
  2165.         # self ** -infinity is infinity if self < 1, 0 if self > 1
  2166.         if other._isinfinity():
  2167.             if (other._sign == 0) == (self_adj < 0):
  2168.                 return _dec_from_triple(result_sign, '0', 0)
  2169.             else:
  2170.                 return _SignedInfinity[result_sign]
  2171.  
  2172.         # from here on, the result always goes through the call
  2173.         # to _fix at the end of this function.
  2174.         ans = None
  2175.  
  2176.         # crude test to catch cases of extreme overflow/underflow.  If
  2177.         # log10(self)*other >= 10**bound and bound >= len(str(Emax))
  2178.         # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
  2179.         # self**other >= 10**(Emax+1), so overflow occurs.  The test
  2180.         # for underflow is similar.
  2181.         bound = self._log10_exp_bound() + other.adjusted()
  2182.         if (self_adj >= 0) == (other._sign == 0):
  2183.             # self > 1 and other +ve, or self < 1 and other -ve
  2184.             # possibility of overflow
  2185.             if bound >= len(str(context.Emax)):
  2186.                 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
  2187.         else:
  2188.             # self > 1 and other -ve, or self < 1 and other +ve
  2189.             # possibility of underflow to 0
  2190.             Etiny = context.Etiny()
  2191.             if bound >= len(str(-Etiny)):
  2192.                 ans = _dec_from_triple(result_sign, '1', Etiny-1)
  2193.  
  2194.         # try for an exact result with precision +1
  2195.         if ans is None:
  2196.             ans = self._power_exact(other, context.prec + 1)
  2197.             if ans is not None and result_sign == 1:
  2198.                 ans = _dec_from_triple(1, ans._int, ans._exp)
  2199.  
  2200.         # usual case: inexact result, x**y computed directly as exp(y*log(x))
  2201.         if ans is None:
  2202.             p = context.prec
  2203.             x = _WorkRep(self)
  2204.             xc, xe = x.int, x.exp
  2205.             y = _WorkRep(other)
  2206.             yc, ye = y.int, y.exp
  2207.             if y.sign == 1:
  2208.                 yc = -yc
  2209.  
  2210.             # compute correctly rounded result:  start with precision +3,
  2211.             # then increase precision until result is unambiguously roundable
  2212.             extra = 3
  2213.             while True:
  2214.                 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
  2215.                 if coeff % (5*10**(len(str(coeff))-p-1)):
  2216.                     break
  2217.                 extra += 3
  2218.  
  2219.             ans = _dec_from_triple(result_sign, str(coeff), exp)
  2220.  
  2221.         # the specification says that for non-integer other we need to
  2222.         # raise Inexact, even when the result is actually exact.  In
  2223.         # the same way, we need to raise Underflow here if the result
  2224.         # is subnormal.  (The call to _fix will take care of raising
  2225.         # Rounded and Subnormal, as usual.)
  2226.         if not other._isinteger():
  2227.             context._raise_error(Inexact)
  2228.             # pad with zeros up to length context.prec+1 if necessary
  2229.             if len(ans._int) <= context.prec:
  2230.                 expdiff = context.prec+1 - len(ans._int)
  2231.                 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
  2232.                                        ans._exp-expdiff)
  2233.             if ans.adjusted() < context.Emin:
  2234.                 context._raise_error(Underflow)
  2235.  
  2236.         # unlike exp, ln and log10, the power function respects the
  2237.         # rounding mode; no need to use ROUND_HALF_EVEN here
  2238.         ans = ans._fix(context)
  2239.         return ans
  2240.  
  2241.     def __rpow__(self, other, context=None):
  2242.         """Swaps self/other and returns __pow__."""
  2243.         other = _convert_other(other)
  2244.         if other is NotImplemented:
  2245.             return other
  2246.         return other.__pow__(self, context=context)
  2247.  
  2248.     def normalize(self, context=None):
  2249.         """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
  2250.  
  2251.         if context is None:
  2252.             context = getcontext()
  2253.  
  2254.         if self._is_special:
  2255.             ans = self._check_nans(context=context)
  2256.             if ans:
  2257.                 return ans
  2258.  
  2259.         dup = self._fix(context)
  2260.         if dup._isinfinity():
  2261.             return dup
  2262.  
  2263.         if not dup:
  2264.             return _dec_from_triple(dup._sign, '0', 0)
  2265.         exp_max = [context.Emax, context.Etop()][context._clamp]
  2266.         end = len(dup._int)
  2267.         exp = dup._exp
  2268.         while dup._int[end-1] == '0' and exp < exp_max:
  2269.             exp += 1
  2270.             end -= 1
  2271.         return _dec_from_triple(dup._sign, dup._int[:end], exp)
  2272.  
  2273.     def quantize(self, exp, rounding=None, context=None, watchexp=True):
  2274.         """Quantize self so its exponent is the same as that of exp.
  2275.  
  2276.         Similar to self._rescale(exp._exp) but with error checking.
  2277.         """
  2278.         exp = _convert_other(exp, raiseit=True)
  2279.  
  2280.         if context is None:
  2281.             context = getcontext()
  2282.         if rounding is None:
  2283.             rounding = context.rounding
  2284.  
  2285.         if self._is_special or exp._is_special:
  2286.             ans = self._check_nans(exp, context)
  2287.             if ans:
  2288.                 return ans
  2289.  
  2290.             if exp._isinfinity() or self._isinfinity():
  2291.                 if exp._isinfinity() and self._isinfinity():
  2292.                     return Decimal(self)  # if both are inf, it is OK
  2293.                 return context._raise_error(InvalidOperation,
  2294.                                         'quantize with one INF')
  2295.  
  2296.         # if we're not watching exponents, do a simple rescale
  2297.         if not watchexp:
  2298.             ans = self._rescale(exp._exp, rounding)
  2299.             # raise Inexact and Rounded where appropriate
  2300.             if ans._exp > self._exp:
  2301.                 context._raise_error(Rounded)
  2302.                 if ans != self:
  2303.                     context._raise_error(Inexact)
  2304.             return ans
  2305.  
  2306.         # exp._exp should be between Etiny and Emax
  2307.         if not (context.Etiny() <= exp._exp <= context.Emax):
  2308.             return context._raise_error(InvalidOperation,
  2309.                    'target exponent out of bounds in quantize')
  2310.  
  2311.         if not self:
  2312.             ans = _dec_from_triple(self._sign, '0', exp._exp)
  2313.             return ans._fix(context)
  2314.  
  2315.         self_adjusted = self.adjusted()
  2316.         if self_adjusted > context.Emax:
  2317.             return context._raise_error(InvalidOperation,
  2318.                                         'exponent of quantize result too large for current context')
  2319.         if self_adjusted - exp._exp + 1 > context.prec:
  2320.             return context._raise_error(InvalidOperation,
  2321.                                         'quantize result has too many digits for current context')
  2322.  
  2323.         ans = self._rescale(exp._exp, rounding)
  2324.         if ans.adjusted() > context.Emax:
  2325.             return context._raise_error(InvalidOperation,
  2326.                                         'exponent of quantize result too large for current context')
  2327.         if len(ans._int) > context.prec:
  2328.             return context._raise_error(InvalidOperation,
  2329.                                         'quantize result has too many digits for current context')
  2330.  
  2331.         # raise appropriate flags
  2332.         if ans._exp > self._exp:
  2333.             context._raise_error(Rounded)
  2334.             if ans != self:
  2335.                 context._raise_error(Inexact)
  2336.         if ans and ans.adjusted() < context.Emin:
  2337.             context._raise_error(Subnormal)
  2338.  
  2339.         # call to fix takes care of any necessary folddown
  2340.         ans = ans._fix(context)
  2341.         return ans
  2342.  
  2343.     def same_quantum(self, other):
  2344.         """Return True if self and other have the same exponent; otherwise
  2345.         return False.
  2346.  
  2347.         If either operand is a special value, the following rules are used:
  2348.            * return True if both operands are infinities
  2349.            * return True if both operands are NaNs
  2350.            * otherwise, return False.
  2351.         """
  2352.         other = _convert_other(other, raiseit=True)
  2353.         if self._is_special or other._is_special:
  2354.             return (self.is_nan() and other.is_nan() or
  2355.                     self.is_infinite() and other.is_infinite())
  2356.         return self._exp == other._exp
  2357.  
  2358.     def _rescale(self, exp, rounding):
  2359.         """Rescale self so that the exponent is exp, either by padding with zeros
  2360.         or by truncating digits, using the given rounding mode.
  2361.  
  2362.         Specials are returned without change.  This operation is
  2363.         quiet: it raises no flags, and uses no information from the
  2364.         context.
  2365.  
  2366.         exp = exp to scale to (an integer)
  2367.         rounding = rounding mode
  2368.         """
  2369.         if self._is_special:
  2370.             return Decimal(self)
  2371.         if not self:
  2372.             return _dec_from_triple(self._sign, '0', exp)
  2373.  
  2374.         if self._exp >= exp:
  2375.             # pad answer with zeros if necessary
  2376.             return _dec_from_triple(self._sign,
  2377.                                         self._int + '0'*(self._exp - exp), exp)
  2378.  
  2379.         # too many digits; round and lose data.  If self.adjusted() <
  2380.         # exp-1, replace self by 10**(exp-1) before rounding
  2381.         digits = len(self._int) + self._exp - exp
  2382.         if digits < 0:
  2383.             self = _dec_from_triple(self._sign, '1', exp-1)
  2384.             digits = 0
  2385.         this_function = getattr(self, self._pick_rounding_function[rounding])
  2386.         changed = this_function(digits)
  2387.         coeff = self._int[:digits] or '0'
  2388.         if changed == 1:
  2389.             coeff = str(int(coeff)+1)
  2390.         return _dec_from_triple(self._sign, coeff, exp)
  2391.  
  2392.     def _round(self, places, rounding):
  2393.         """Round a nonzero, nonspecial Decimal to a fixed number of
  2394.         significant figures, using the given rounding mode.
  2395.  
  2396.         Infinities, NaNs and zeros are returned unaltered.
  2397.  
  2398.         This operation is quiet: it raises no flags, and uses no
  2399.         information from the context.
  2400.  
  2401.         """
  2402.         if places <= 0:
  2403.             raise ValueError("argument should be at least 1 in _round")
  2404.         if self._is_special or not self:
  2405.             return Decimal(self)
  2406.         ans = self._rescale(self.adjusted()+1-places, rounding)
  2407.         # it can happen that the rescale alters the adjusted exponent;
  2408.         # for example when rounding 99.97 to 3 significant figures.
  2409.         # When this happens we end up with an extra 0 at the end of
  2410.         # the number; a second rescale fixes this.
  2411.         if ans.adjusted() != self.adjusted():
  2412.             ans = ans._rescale(ans.adjusted()+1-places, rounding)
  2413.         return ans
  2414.  
  2415.     def to_integral_exact(self, rounding=None, context=None):
  2416.         """Rounds to a nearby integer.
  2417.  
  2418.         If no rounding mode is specified, take the rounding mode from
  2419.         the context.  This method raises the Rounded and Inexact flags
  2420.         when appropriate.
  2421.  
  2422.         See also: to_integral_value, which does exactly the same as
  2423.         this method except that it doesn't raise Inexact or Rounded.
  2424.         """
  2425.         if self._is_special:
  2426.             ans = self._check_nans(context=context)
  2427.             if ans:
  2428.                 return ans
  2429.             return Decimal(self)
  2430.         if self._exp >= 0:
  2431.             return Decimal(self)
  2432.         if not self:
  2433.             return _dec_from_triple(self._sign, '0', 0)
  2434.         if context is None:
  2435.             context = getcontext()
  2436.         if rounding is None:
  2437.             rounding = context.rounding
  2438.         context._raise_error(Rounded)
  2439.         ans = self._rescale(0, rounding)
  2440.         if ans != self:
  2441.             context._raise_error(Inexact)
  2442.         return ans
  2443.  
  2444.     def to_integral_value(self, rounding=None, context=None):
  2445.         """Rounds to the nearest integer, without raising inexact, rounded."""
  2446.         if context is None:
  2447.             context = getcontext()
  2448.         if rounding is None:
  2449.             rounding = context.rounding
  2450.         if self._is_special:
  2451.             ans = self._check_nans(context=context)
  2452.             if ans:
  2453.                 return ans
  2454.             return Decimal(self)
  2455.         if self._exp >= 0:
  2456.             return Decimal(self)
  2457.         else:
  2458.             return self._rescale(0, rounding)
  2459.  
  2460.     # the method name changed, but we provide also the old one, for compatibility
  2461.     to_integral = to_integral_value
  2462.  
  2463.     def sqrt(self, context=None):
  2464.         """Return the square root of self."""
  2465.         if context is None:
  2466.             context = getcontext()
  2467.  
  2468.         if self._is_special:
  2469.             ans = self._check_nans(context=context)
  2470.             if ans:
  2471.                 return ans
  2472.  
  2473.             if self._isinfinity() and self._sign == 0:
  2474.                 return Decimal(self)
  2475.  
  2476.         if not self:
  2477.             # exponent = self._exp // 2.  sqrt(-0) = -0
  2478.             ans = _dec_from_triple(self._sign, '0', self._exp // 2)
  2479.             return ans._fix(context)
  2480.  
  2481.         if self._sign == 1:
  2482.             return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
  2483.  
  2484.         # At this point self represents a positive number.  Let p be
  2485.         # the desired precision and express self in the form c*100**e
  2486.         # with c a positive real number and e an integer, c and e
  2487.         # being chosen so that 100**(p-1) <= c < 100**p.  Then the
  2488.         # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
  2489.         # <= sqrt(c) < 10**p, so the closest representable Decimal at
  2490.         # precision p is n*10**e where n = round_half_even(sqrt(c)),
  2491.         # the closest integer to sqrt(c) with the even integer chosen
  2492.         # in the case of a tie.
  2493.         #
  2494.         # To ensure correct rounding in all cases, we use the
  2495.         # following trick: we compute the square root to an extra
  2496.         # place (precision p+1 instead of precision p), rounding down.
  2497.         # Then, if the result is inexact and its last digit is 0 or 5,
  2498.         # we increase the last digit to 1 or 6 respectively; if it's
  2499.         # exact we leave the last digit alone.  Now the final round to
  2500.         # p places (or fewer in the case of underflow) will round
  2501.         # correctly and raise the appropriate flags.
  2502.  
  2503.         # use an extra digit of precision
  2504.         prec = context.prec+1
  2505.  
  2506.         # write argument in the form c*100**e where e = self._exp//2
  2507.         # is the 'ideal' exponent, to be used if the square root is
  2508.         # exactly representable.  l is the number of 'digits' of c in
  2509.         # base 100, so that 100**(l-1) <= c < 100**l.
  2510.         op = _WorkRep(self)
  2511.         e = op.exp >> 1
  2512.         if op.exp & 1:
  2513.             c = op.int * 10
  2514.             l = (len(self._int) >> 1) + 1
  2515.         else:
  2516.             c = op.int
  2517.             l = len(self._int)+1 >> 1
  2518.  
  2519.         # rescale so that c has exactly prec base 100 'digits'
  2520.         shift = prec-l
  2521.         if shift >= 0:
  2522.             c *= 100**shift
  2523.             exact = True
  2524.         else:
  2525.             c, remainder = divmod(c, 100**-shift)
  2526.             exact = not remainder
  2527.         e -= shift
  2528.  
  2529.         # find n = floor(sqrt(c)) using Newton's method
  2530.         n = 10**prec
  2531.         while True:
  2532.             q = c//n
  2533.             if n <= q:
  2534.                 break
  2535.             else:
  2536.                 n = n + q >> 1
  2537.         exact = exact and n*n == c
  2538.  
  2539.         if exact:
  2540.             # result is exact; rescale to use ideal exponent e
  2541.             if shift >= 0:
  2542.                 # assert n % 10**shift == 0
  2543.                 n //= 10**shift
  2544.             else:
  2545.                 n *= 10**-shift
  2546.             e += shift
  2547.         else:
  2548.             # result is not exact; fix last digit as described above
  2549.             if n % 5 == 0:
  2550.                 n += 1
  2551.  
  2552.         ans = _dec_from_triple(0, str(n), e)
  2553.  
  2554.         # round, and fit to current context
  2555.         context = context._shallow_copy()
  2556.         rounding = context._set_rounding(ROUND_HALF_EVEN)
  2557.         ans = ans._fix(context)
  2558.         context.rounding = rounding
  2559.  
  2560.         return ans
  2561.  
  2562.     def max(self, other, context=None):
  2563.         """Returns the larger value.
  2564.  
  2565.         Like max(self, other) except if one is not a number, returns
  2566.         NaN (and signals if one is sNaN).  Also rounds.
  2567.         """
  2568.         other = _convert_other(other, raiseit=True)
  2569.  
  2570.         if context is None:
  2571.             context = getcontext()
  2572.  
  2573.         if self._is_special or other._is_special:
  2574.             # If one operand is a quiet NaN and the other is number, then the
  2575.             # number is always returned
  2576.             sn = self._isnan()
  2577.             on = other._isnan()
  2578.             if sn or on:
  2579.                 if on == 1 and sn == 0:
  2580.                     return self._fix(context)
  2581.                 if sn == 1 and on == 0:
  2582.                     return other._fix(context)
  2583.                 return self._check_nans(other, context)
  2584.  
  2585.         c = self._cmp(other)
  2586.         if c == 0:
  2587.             # If both operands are finite and equal in numerical value
  2588.             # then an ordering is applied:
  2589.             #
  2590.             # If the signs differ then max returns the operand with the
  2591.             # positive sign and min returns the operand with the negative sign
  2592.             #
  2593.             # If the signs are the same then the exponent is used to select
  2594.             # the result.  This is exactly the ordering used in compare_total.
  2595.             c = self.compare_total(other)
  2596.  
  2597.         if c == -1:
  2598.             ans = other
  2599.         else:
  2600.             ans = self
  2601.  
  2602.         return ans._fix(context)
  2603.  
  2604.     def min(self, other, context=None):
  2605.         """Returns the smaller value.
  2606.  
  2607.         Like min(self, other) except if one is not a number, returns
  2608.         NaN (and signals if one is sNaN).  Also rounds.
  2609.         """
  2610.         other = _convert_other(other, raiseit=True)
  2611.  
  2612.         if context is None:
  2613.             context = getcontext()
  2614.  
  2615.         if self._is_special or other._is_special:
  2616.             # If one operand is a quiet NaN and the other is number, then the
  2617.             # number is always returned
  2618.             sn = self._isnan()
  2619.             on = other._isnan()
  2620.             if sn or on:
  2621.                 if on == 1 and sn == 0:
  2622.                     return self._fix(context)
  2623.                 if sn == 1 and on == 0:
  2624.                     return other._fix(context)
  2625.                 return self._check_nans(other, context)
  2626.  
  2627.         c = self._cmp(other)
  2628.         if c == 0:
  2629.             c = self.compare_total(other)
  2630.  
  2631.         if c == -1:
  2632.             ans = self
  2633.         else:
  2634.             ans = other
  2635.  
  2636.         return ans._fix(context)
  2637.  
  2638.     def _isinteger(self):
  2639.         """Returns whether self is an integer"""
  2640.         if self._is_special:
  2641.             return False
  2642.         if self._exp >= 0:
  2643.             return True
  2644.         rest = self._int[self._exp:]
  2645.         return rest == '0'*len(rest)
  2646.  
  2647.     def _iseven(self):
  2648.         """Returns True if self is even.  Assumes self is an integer."""
  2649.         if not self or self._exp > 0:
  2650.             return True
  2651.         return self._int[-1+self._exp] in '02468'
  2652.  
  2653.     def adjusted(self):
  2654.         """Return the adjusted exponent of self"""
  2655.         try:
  2656.             return self._exp + len(self._int) - 1
  2657.         # If NaN or Infinity, self._exp is string
  2658.         except TypeError:
  2659.             return 0
  2660.  
  2661.     def canonical(self, context=None):
  2662.         """Returns the same Decimal object.
  2663.  
  2664.         As we do not have different encodings for the same number, the
  2665.         received object already is in its canonical form.
  2666.         """
  2667.         return self
  2668.  
  2669.     def compare_signal(self, other, context=None):
  2670.         """Compares self to the other operand numerically.
  2671.  
  2672.         It's pretty much like compare(), but all NaNs signal, with signaling
  2673.         NaNs taking precedence over quiet NaNs.
  2674.         """
  2675.         other = _convert_other(other, raiseit = True)
  2676.         ans = self._compare_check_nans(other, context)
  2677.         if ans:
  2678.             return ans
  2679.         return self.compare(other, context=context)
  2680.  
  2681.     def compare_total(self, other):
  2682.         """Compares self to other using the abstract representations.
  2683.  
  2684.         This is not like the standard compare, which use their numerical
  2685.         value. Note that a total ordering is defined for all possible abstract
  2686.         representations.
  2687.         """
  2688.         # if one is negative and the other is positive, it's easy
  2689.         if self._sign and not other._sign:
  2690.             return _NegativeOne
  2691.         if not self._sign and other._sign:
  2692.             return _One
  2693.         sign = self._sign
  2694.  
  2695.         # let's handle both NaN types
  2696.         self_nan = self._isnan()
  2697.         other_nan = other._isnan()
  2698.         if self_nan or other_nan:
  2699.             if self_nan == other_nan:
  2700.                 if self._int < other._int:
  2701.                     if sign:
  2702.                         return _One
  2703.                     else:
  2704.                         return _NegativeOne
  2705.                 if self._int > other._int:
  2706.                     if sign:
  2707.                         return _NegativeOne
  2708.                     else:
  2709.                         return _One
  2710.                 return _Zero
  2711.  
  2712.             if sign:
  2713.                 if self_nan == 1:
  2714.                     return _NegativeOne
  2715.                 if other_nan == 1:
  2716.                     return _One
  2717.                 if self_nan == 2:
  2718.                     return _NegativeOne
  2719.                 if other_nan == 2:
  2720.                     return _One
  2721.             else:
  2722.                 if self_nan == 1:
  2723.                     return _One
  2724.                 if other_nan == 1:
  2725.                     return _NegativeOne
  2726.                 if self_nan == 2:
  2727.                     return _One
  2728.                 if other_nan == 2:
  2729.                     return _NegativeOne
  2730.  
  2731.         if self < other:
  2732.             return _NegativeOne
  2733.         if self > other:
  2734.             return _One
  2735.  
  2736.         if self._exp < other._exp:
  2737.             if sign:
  2738.                 return _One
  2739.             else:
  2740.                 return _NegativeOne
  2741.         if self._exp > other._exp:
  2742.             if sign:
  2743.                 return _NegativeOne
  2744.             else:
  2745.                 return _One
  2746.         return _Zero
  2747.  
  2748.  
  2749.     def compare_total_mag(self, other):
  2750.         """Compares self to other using abstract repr., ignoring sign.
  2751.  
  2752.         Like compare_total, but with operand's sign ignored and assumed to be 0.
  2753.         """
  2754.         s = self.copy_abs()
  2755.         o = other.copy_abs()
  2756.         return s.compare_total(o)
  2757.  
  2758.     def copy_abs(self):
  2759.         """Returns a copy with the sign set to 0. """
  2760.         return _dec_from_triple(0, self._int, self._exp, self._is_special)
  2761.  
  2762.     def copy_negate(self):
  2763.         """Returns a copy with the sign inverted."""
  2764.         if self._sign:
  2765.             return _dec_from_triple(0, self._int, self._exp, self._is_special)
  2766.         else:
  2767.             return _dec_from_triple(1, self._int, self._exp, self._is_special)
  2768.  
  2769.     def copy_sign(self, other):
  2770.         """Returns self with the sign of other."""
  2771.         return _dec_from_triple(other._sign, self._int,
  2772.                                 self._exp, self._is_special)
  2773.  
  2774.     def exp(self, context=None):
  2775.         """Returns e ** self."""
  2776.  
  2777.         if context is None:
  2778.             context = getcontext()
  2779.  
  2780.         # exp(NaN) = NaN
  2781.         ans = self._check_nans(context=context)
  2782.         if ans:
  2783.             return ans
  2784.  
  2785.         # exp(-Infinity) = 0
  2786.         if self._isinfinity() == -1:
  2787.             return _Zero
  2788.  
  2789.         # exp(0) = 1
  2790.         if not self:
  2791.             return _One
  2792.  
  2793.         # exp(Infinity) = Infinity
  2794.         if self._isinfinity() == 1:
  2795.             return Decimal(self)
  2796.  
  2797.         # the result is now guaranteed to be inexact (the true
  2798.         # mathematical result is transcendental). There's no need to
  2799.         # raise Rounded and Inexact here---they'll always be raised as
  2800.         # a result of the call to _fix.
  2801.         p = context.prec
  2802.         adj = self.adjusted()
  2803.  
  2804.         # we only need to do any computation for quite a small range
  2805.         # of adjusted exponents---for example, -29 <= adj <= 10 for
  2806.         # the default context.  For smaller exponent the result is
  2807.         # indistinguishable from 1 at the given precision, while for
  2808.         # larger exponent the result either overflows or underflows.
  2809.         if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
  2810.             # overflow
  2811.             ans = _dec_from_triple(0, '1', context.Emax+1)
  2812.         elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
  2813.             # underflow to 0
  2814.             ans = _dec_from_triple(0, '1', context.Etiny()-1)
  2815.         elif self._sign == 0 and adj < -p:
  2816.             # p+1 digits; final round will raise correct flags
  2817.             ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
  2818.         elif self._sign == 1 and adj < -p-1:
  2819.             # p+1 digits; final round will raise correct flags
  2820.             ans = _dec_from_triple(0, '9'*(p+1), -p-1)
  2821.         # general case
  2822.         else:
  2823.             op = _WorkRep(self)
  2824.             c, e = op.int, op.exp
  2825.             if op.sign == 1:
  2826.                 c = -c
  2827.  
  2828.             # compute correctly rounded result: increase precision by
  2829.             # 3 digits at a time until we get an unambiguously
  2830.             # roundable result
  2831.             extra = 3
  2832.             while True:
  2833.                 coeff, exp = _dexp(c, e, p+extra)
  2834.                 if coeff % (5*10**(len(str(coeff))-p-1)):
  2835.                     break
  2836.                 extra += 3
  2837.  
  2838.             ans = _dec_from_triple(0, str(coeff), exp)
  2839.  
  2840.         # at this stage, ans should round correctly with *any*
  2841.         # rounding mode, not just with ROUND_HALF_EVEN
  2842.         context = context._shallow_copy()
  2843.         rounding = context._set_rounding(ROUND_HALF_EVEN)
  2844.         ans = ans._fix(context)
  2845.         context.rounding = rounding
  2846.  
  2847.         return ans
  2848.  
  2849.     def is_canonical(self):
  2850.         """Return True if self is canonical; otherwise return False.
  2851.  
  2852.         Currently, the encoding of a Decimal instance is always
  2853.         canonical, so this method returns True for any Decimal.
  2854.         """
  2855.         return True
  2856.  
  2857.     def is_finite(self):
  2858.         """Return True if self is finite; otherwise return False.
  2859.  
  2860.         A Decimal instance is considered finite if it is neither
  2861.         infinite nor a NaN.
  2862.         """
  2863.         return not self._is_special
  2864.  
  2865.     def is_infinite(self):
  2866.         """Return True if self is infinite; otherwise return False."""
  2867.         return self._exp == 'F'
  2868.  
  2869.     def is_nan(self):
  2870.         """Return True if self is a qNaN or sNaN; otherwise return False."""
  2871.         return self._exp in ('n', 'N')
  2872.  
  2873.     def is_normal(self, context=None):
  2874.         """Return True if self is a normal number; otherwise return False."""
  2875.         if self._is_special or not self:
  2876.             return False
  2877.         if context is None:
  2878.             context = getcontext()
  2879.         return context.Emin <= self.adjusted() <= context.Emax
  2880.  
  2881.     def is_qnan(self):
  2882.         """Return True if self is a quiet NaN; otherwise return False."""
  2883.         return self._exp == 'n'
  2884.  
  2885.     def is_signed(self):
  2886.         """Return True if self is negative; otherwise return False."""
  2887.         return self._sign == 1
  2888.  
  2889.     def is_snan(self):
  2890.         """Return True if self is a signaling NaN; otherwise return False."""
  2891.         return self._exp == 'N'
  2892.  
  2893.     def is_subnormal(self, context=None):
  2894.         """Return True if self is subnormal; otherwise return False."""
  2895.         if self._is_special or not self:
  2896.             return False
  2897.         if context is None:
  2898.             context = getcontext()
  2899.         return self.adjusted() < context.Emin
  2900.  
  2901.     def is_zero(self):
  2902.         """Return True if self is a zero; otherwise return False."""
  2903.         return not self._is_special and self._int == '0'
  2904.  
  2905.     def _ln_exp_bound(self):
  2906.         """Compute a lower bound for the adjusted exponent of self.ln().
  2907.         In other words, compute r such that self.ln() >= 10**r.  Assumes
  2908.         that self is finite and positive and that self != 1.
  2909.         """
  2910.  
  2911.         # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
  2912.         adj = self._exp + len(self._int) - 1
  2913.         if adj >= 1:
  2914.             # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
  2915.             return len(str(adj*23//10)) - 1
  2916.         if adj <= -2:
  2917.             # argument <= 0.1
  2918.             return len(str((-1-adj)*23//10)) - 1
  2919.         op = _WorkRep(self)
  2920.         c, e = op.int, op.exp
  2921.         if adj == 0:
  2922.             # 1 < self < 10
  2923.             num = str(c-10**-e)
  2924.             den = str(c)
  2925.             return len(num) - len(den) - (num < den)
  2926.         # adj == -1, 0.1 <= self < 1
  2927.         return e + len(str(10**-e - c)) - 1
  2928.  
  2929.  
  2930.     def ln(self, context=None):
  2931.         """Returns the natural (base e) logarithm of self."""
  2932.  
  2933.         if context is None:
  2934.             context = getcontext()
  2935.  
  2936.         # ln(NaN) = NaN
  2937.         ans = self._check_nans(context=context)
  2938.         if ans:
  2939.             return ans
  2940.  
  2941.         # ln(0.0) == -Infinity
  2942.         if not self:
  2943.             return _NegativeInfinity
  2944.  
  2945.         # ln(Infinity) = Infinity
  2946.         if self._isinfinity() == 1:
  2947.             return _Infinity
  2948.  
  2949.         # ln(1.0) == 0.0
  2950.         if self == _One:
  2951.             return _Zero
  2952.  
  2953.         # ln(negative) raises InvalidOperation
  2954.         if self._sign == 1:
  2955.             return context._raise_error(InvalidOperation,
  2956.                                         'ln of a negative value')
  2957.  
  2958.         # result is irrational, so necessarily inexact
  2959.         op = _WorkRep(self)
  2960.         c, e = op.int, op.exp
  2961.         p = context.prec
  2962.  
  2963.         # correctly rounded result: repeatedly increase precision by 3
  2964.         # until we get an unambiguously roundable result
  2965.         places = p - self._ln_exp_bound() + 2 # at least p+3 places
  2966.         while True:
  2967.             coeff = _dlog(c, e, places)
  2968.             # assert len(str(abs(coeff)))-p >= 1
  2969.             if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
  2970.                 break
  2971.             places += 3
  2972.         ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
  2973.  
  2974.         context = context._shallow_copy()
  2975.         rounding = context._set_rounding(ROUND_HALF_EVEN)
  2976.         ans = ans._fix(context)
  2977.         context.rounding = rounding
  2978.         return ans
  2979.  
  2980.     def _log10_exp_bound(self):
  2981.         """Compute a lower bound for the adjusted exponent of self.log10().
  2982.         In other words, find r such that self.log10() >= 10**r.
  2983.         Assumes that self is finite and positive and that self != 1.
  2984.         """
  2985.  
  2986.         # For x >= 10 or x < 0.1 we only need a bound on the integer
  2987.         # part of log10(self), and this comes directly from the
  2988.         # exponent of x.  For 0.1 <= x <= 10 we use the inequalities
  2989.         # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
  2990.         # (1-1/x)/2.31 > 0.  If x < 1 then |log10(x)| > (1-x)/2.31 > 0
  2991.  
  2992.         adj = self._exp + len(self._int) - 1
  2993.         if adj >= 1:
  2994.             # self >= 10
  2995.             return len(str(adj))-1
  2996.         if adj <= -2:
  2997.             # self < 0.1
  2998.             return len(str(-1-adj))-1
  2999.         op = _WorkRep(self)
  3000.         c, e = op.int, op.exp
  3001.         if adj == 0:
  3002.             # 1 < self < 10
  3003.             num = str(c-10**-e)
  3004.             den = str(231*c)
  3005.             return len(num) - len(den) - (num < den) + 2
  3006.         # adj == -1, 0.1 <= self < 1
  3007.         num = str(10**-e-c)
  3008.         return len(num) + e - (num < "231") - 1
  3009.  
  3010.     def log10(self, context=None):
  3011.         """Returns the base 10 logarithm of self."""
  3012.  
  3013.         if context is None:
  3014.             context = getcontext()
  3015.  
  3016.         # log10(NaN) = NaN
  3017.         ans = self._check_nans(context=context)
  3018.         if ans:
  3019.             return ans
  3020.  
  3021.         # log10(0.0) == -Infinity
  3022.         if not self:
  3023.             return _NegativeInfinity
  3024.  
  3025.         # log10(Infinity) = Infinity
  3026.         if self._isinfinity() == 1:
  3027.             return _Infinity
  3028.  
  3029.         # log10(negative or -Infinity) raises InvalidOperation
  3030.         if self._sign == 1:
  3031.             return context._raise_error(InvalidOperation,
  3032.                                         'log10 of a negative value')
  3033.  
  3034.         # log10(10**n) = n
  3035.         if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
  3036.             # answer may need rounding
  3037.             ans = Decimal(self._exp + len(self._int) - 1)
  3038.         else:
  3039.             # result is irrational, so necessarily inexact
  3040.             op = _WorkRep(self)
  3041.             c, e = op.int, op.exp
  3042.             p = context.prec
  3043.  
  3044.             # correctly rounded result: repeatedly increase precision
  3045.             # until result is unambiguously roundable
  3046.             places = p-self._log10_exp_bound()+2
  3047.             while True:
  3048.                 coeff = _dlog10(c, e, places)
  3049.                 # assert len(str(abs(coeff)))-p >= 1
  3050.                 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
  3051.                     break
  3052.                 places += 3
  3053.             ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
  3054.  
  3055.         context = context._shallow_copy()
  3056.         rounding = context._set_rounding(ROUND_HALF_EVEN)
  3057.         ans = ans._fix(context)
  3058.         context.rounding = rounding
  3059.         return ans
  3060.  
  3061.     def logb(self, context=None):
  3062.         """ Returns the exponent of the magnitude of self's MSD.
  3063.  
  3064.         The result is the integer which is the exponent of the magnitude
  3065.         of the most significant digit of self (as though it were truncated
  3066.         to a single digit while maintaining the value of that digit and
  3067.         without limiting the resulting exponent).
  3068.         """
  3069.         # logb(NaN) = NaN
  3070.         ans = self._check_nans(context=context)
  3071.         if ans:
  3072.             return ans
  3073.  
  3074.         if context is None:
  3075.             context = getcontext()
  3076.  
  3077.         # logb(+/-Inf) = +Inf
  3078.         if self._isinfinity():
  3079.             return _Infinity
  3080.  
  3081.         # logb(0) = -Inf, DivisionByZero
  3082.         if not self:
  3083.             return context._raise_error(DivisionByZero, 'logb(0)', 1)
  3084.  
  3085.         # otherwise, simply return the adjusted exponent of self, as a
  3086.         # Decimal.  Note that no attempt is made to fit the result
  3087.         # into the current context.
  3088.         return Decimal(self.adjusted())
  3089.  
  3090.     def _islogical(self):
  3091.         """Return True if self is a logical operand.
  3092.  
  3093.         For being logical, it must be a finite number with a sign of 0,
  3094.         an exponent of 0, and a coefficient whose digits must all be
  3095.         either 0 or 1.
  3096.         """
  3097.         if self._sign != 0 or self._exp != 0:
  3098.             return False
  3099.         for dig in self._int:
  3100.             if dig not in '01':
  3101.                 return False
  3102.         return True
  3103.  
  3104.     def _fill_logical(self, context, opa, opb):
  3105.         dif = context.prec - len(opa)
  3106.         if dif > 0:
  3107.             opa = '0'*dif + opa
  3108.         elif dif < 0:
  3109.             opa = opa[-context.prec:]
  3110.         dif = context.prec - len(opb)
  3111.         if dif > 0:
  3112.             opb = '0'*dif + opb
  3113.         elif dif < 0:
  3114.             opb = opb[-context.prec:]
  3115.         return opa, opb
  3116.  
  3117.     def logical_and(self, other, context=None):
  3118.         """Applies an 'and' operation between self and other's digits."""
  3119.         if context is None:
  3120.             context = getcontext()
  3121.         if not self._islogical() or not other._islogical():
  3122.             return context._raise_error(InvalidOperation)
  3123.  
  3124.         # fill to context.prec
  3125.         (opa, opb) = self._fill_logical(context, self._int, other._int)
  3126.  
  3127.         # make the operation, and clean starting zeroes
  3128.         result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
  3129.         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
  3130.  
  3131.     def logical_invert(self, context=None):
  3132.         """Invert all its digits."""
  3133.         if context is None:
  3134.             context = getcontext()
  3135.         return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
  3136.                                 context)
  3137.  
  3138.     def logical_or(self, other, context=None):
  3139.         """Applies an 'or' operation between self and other's digits."""
  3140.         if context is None:
  3141.             context = getcontext()
  3142.         if not self._islogical() or not other._islogical():
  3143.             return context._raise_error(InvalidOperation)
  3144.  
  3145.         # fill to context.prec
  3146.         (opa, opb) = self._fill_logical(context, self._int, other._int)
  3147.  
  3148.         # make the operation, and clean starting zeroes
  3149.         result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
  3150.         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
  3151.  
  3152.     def logical_xor(self, other, context=None):
  3153.         """Applies an 'xor' operation between self and other's digits."""
  3154.         if context is None:
  3155.             context = getcontext()
  3156.         if not self._islogical() or not other._islogical():
  3157.             return context._raise_error(InvalidOperation)
  3158.  
  3159.         # fill to context.prec
  3160.         (opa, opb) = self._fill_logical(context, self._int, other._int)
  3161.  
  3162.         # make the operation, and clean starting zeroes
  3163.         result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
  3164.         return _dec_from_triple(0, result.lstrip('0') or '0', 0)
  3165.  
  3166.     def max_mag(self, other, context=None):
  3167.         """Compares the values numerically with their sign ignored."""
  3168.         other = _convert_other(other, raiseit=True)
  3169.  
  3170.         if context is None:
  3171.             context = getcontext()
  3172.  
  3173.         if self._is_special or other._is_special:
  3174.             # If one operand is a quiet NaN and the other is number, then the
  3175.             # number is always returned
  3176.             sn = self._isnan()
  3177.             on = other._isnan()
  3178.             if sn or on:
  3179.                 if on == 1 and sn == 0:
  3180.                     return self._fix(context)
  3181.                 if sn == 1 and on == 0:
  3182.                     return other._fix(context)
  3183.                 return self._check_nans(other, context)
  3184.  
  3185.         c = self.copy_abs()._cmp(other.copy_abs())
  3186.         if c == 0:
  3187.             c = self.compare_total(other)
  3188.  
  3189.         if c == -1:
  3190.             ans = other
  3191.         else:
  3192.             ans = self
  3193.  
  3194.         return ans._fix(context)
  3195.  
  3196.     def min_mag(self, other, context=None):
  3197.         """Compares the values numerically with their sign ignored."""
  3198.         other = _convert_other(other, raiseit=True)
  3199.  
  3200.         if context is None:
  3201.             context = getcontext()
  3202.  
  3203.         if self._is_special or other._is_special:
  3204.             # If one operand is a quiet NaN and the other is number, then the
  3205.             # number is always returned
  3206.             sn = self._isnan()
  3207.             on = other._isnan()
  3208.             if sn or on:
  3209.                 if on == 1 and sn == 0:
  3210.                     return self._fix(context)
  3211.                 if sn == 1 and on == 0:
  3212.                     return other._fix(context)
  3213.                 return self._check_nans(other, context)
  3214.  
  3215.         c = self.copy_abs()._cmp(other.copy_abs())
  3216.         if c == 0:
  3217.             c = self.compare_total(other)
  3218.  
  3219.         if c == -1:
  3220.             ans = self
  3221.         else:
  3222.             ans = other
  3223.  
  3224.         return ans._fix(context)
  3225.  
  3226.     def next_minus(self, context=None):
  3227.         """Returns the largest representable number smaller than itself."""
  3228.         if context is None:
  3229.             context = getcontext()
  3230.  
  3231.         ans = self._check_nans(context=context)
  3232.         if ans:
  3233.             return ans
  3234.  
  3235.         if self._isinfinity() == -1:
  3236.             return _NegativeInfinity
  3237.         if self._isinfinity() == 1:
  3238.             return _dec_from_triple(0, '9'*context.prec, context.Etop())
  3239.  
  3240.         context = context.copy()
  3241.         context._set_rounding(ROUND_FLOOR)
  3242.         context._ignore_all_flags()
  3243.         new_self = self._fix(context)
  3244.         if new_self != self:
  3245.             return new_self
  3246.         return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
  3247.                             context)
  3248.  
  3249.     def next_plus(self, context=None):
  3250.         """Returns the smallest representable number larger than itself."""
  3251.         if context is None:
  3252.             context = getcontext()
  3253.  
  3254.         ans = self._check_nans(context=context)
  3255.         if ans:
  3256.             return ans
  3257.  
  3258.         if self._isinfinity() == 1:
  3259.             return _Infinity
  3260.         if self._isinfinity() == -1:
  3261.             return _dec_from_triple(1, '9'*context.prec, context.Etop())
  3262.  
  3263.         context = context.copy()
  3264.         context._set_rounding(ROUND_CEILING)
  3265.         context._ignore_all_flags()
  3266.         new_self = self._fix(context)
  3267.         if new_self != self:
  3268.             return new_self
  3269.         return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
  3270.                             context)
  3271.  
  3272.     def next_toward(self, other, context=None):
  3273.         """Returns the number closest to self, in the direction towards other.
  3274.  
  3275.         The result is the closest representable number to self
  3276.         (excluding self) that is in the direction towards other,
  3277.         unless both have the same value.  If the two operands are
  3278.         numerically equal, then the result is a copy of self with the
  3279.         sign set to be the same as the sign of other.
  3280.         """
  3281.         other = _convert_other(other, raiseit=True)
  3282.  
  3283.         if context is None:
  3284.             context = getcontext()
  3285.  
  3286.         ans = self._check_nans(other, context)
  3287.         if ans:
  3288.             return ans
  3289.  
  3290.         comparison = self._cmp(other)
  3291.         if comparison == 0:
  3292.             return self.copy_sign(other)
  3293.  
  3294.         if comparison == -1:
  3295.             ans = self.next_plus(context)
  3296.         else: # comparison == 1
  3297.             ans = self.next_minus(context)
  3298.  
  3299.         # decide which flags to raise using value of ans
  3300.         if ans._isinfinity():
  3301.             context._raise_error(Overflow,
  3302.                                  'Infinite result from next_toward',
  3303.                                  ans._sign)
  3304.             context._raise_error(Rounded)
  3305.             context._raise_error(Inexact)
  3306.         elif ans.adjusted() < context.Emin:
  3307.             context._raise_error(Underflow)
  3308.             context._raise_error(Subnormal)
  3309.             context._raise_error(Rounded)
  3310.             context._raise_error(Inexact)
  3311.             # if precision == 1 then we don't raise Clamped for a
  3312.             # result 0E-Etiny.
  3313.             if not ans:
  3314.                 context._raise_error(Clamped)
  3315.  
  3316.         return ans
  3317.  
  3318.     def number_class(self, context=None):
  3319.         """Returns an indication of the class of self.
  3320.  
  3321.         The class is one of the following strings:
  3322.           sNaN
  3323.           NaN
  3324.           -Infinity
  3325.           -Normal
  3326.           -Subnormal
  3327.           -Zero
  3328.           +Zero
  3329.           +Subnormal
  3330.           +Normal
  3331.           +Infinity
  3332.         """
  3333.         if self.is_snan():
  3334.             return "sNaN"
  3335.         if self.is_qnan():
  3336.             return "NaN"
  3337.         inf = self._isinfinity()
  3338.         if inf == 1:
  3339.             return "+Infinity"
  3340.         if inf == -1:
  3341.             return "-Infinity"
  3342.         if self.is_zero():
  3343.             if self._sign:
  3344.                 return "-Zero"
  3345.             else:
  3346.                 return "+Zero"
  3347.         if context is None:
  3348.             context = getcontext()
  3349.         if self.is_subnormal(context=context):
  3350.             if self._sign:
  3351.                 return "-Subnormal"
  3352.             else:
  3353.                 return "+Subnormal"
  3354.         # just a normal, regular, boring number, :)
  3355.         if self._sign:
  3356.             return "-Normal"
  3357.         else:
  3358.             return "+Normal"
  3359.  
  3360.     def radix(self):
  3361.         """Just returns 10, as this is Decimal, :)"""
  3362.         return Decimal(10)
  3363.  
  3364.     def rotate(self, other, context=None):
  3365.         """Returns a rotated copy of self, value-of-other times."""
  3366.         if context is None:
  3367.             context = getcontext()
  3368.  
  3369.         ans = self._check_nans(other, context)
  3370.         if ans:
  3371.             return ans
  3372.  
  3373.         if other._exp != 0:
  3374.             return context._raise_error(InvalidOperation)
  3375.         if not (-context.prec <= int(other) <= context.prec):
  3376.             return context._raise_error(InvalidOperation)
  3377.  
  3378.         if self._isinfinity():
  3379.             return Decimal(self)
  3380.  
  3381.         # get values, pad if necessary
  3382.         torot = int(other)
  3383.         rotdig = self._int
  3384.         topad = context.prec - len(rotdig)
  3385.         if topad:
  3386.             rotdig = '0'*topad + rotdig
  3387.  
  3388.         # let's rotate!
  3389.         rotated = rotdig[torot:] + rotdig[:torot]
  3390.         return _dec_from_triple(self._sign,
  3391.                                 rotated.lstrip('0') or '0', self._exp)
  3392.  
  3393.     def scaleb (self, other, context=None):
  3394.         """Returns self operand after adding the second value to its exp."""
  3395.         if context is None:
  3396.             context = getcontext()
  3397.  
  3398.         ans = self._check_nans(other, context)
  3399.         if ans:
  3400.             return ans
  3401.  
  3402.         if other._exp != 0:
  3403.             return context._raise_error(InvalidOperation)
  3404.         liminf = -2 * (context.Emax + context.prec)
  3405.         limsup =  2 * (context.Emax + context.prec)
  3406.         if not (liminf <= int(other) <= limsup):
  3407.             return context._raise_error(InvalidOperation)
  3408.  
  3409.         if self._isinfinity():
  3410.             return Decimal(self)
  3411.  
  3412.         d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
  3413.         d = d._fix(context)
  3414.         return d
  3415.  
  3416.     def shift(self, other, context=None):
  3417.         """Returns a shifted copy of self, value-of-other times."""
  3418.         if context is None:
  3419.             context = getcontext()
  3420.  
  3421.         ans = self._check_nans(other, context)
  3422.         if ans:
  3423.             return ans
  3424.  
  3425.         if other._exp != 0:
  3426.             return context._raise_error(InvalidOperation)
  3427.         if not (-context.prec <= int(other) <= context.prec):
  3428.             return context._raise_error(InvalidOperation)
  3429.  
  3430.         if self._isinfinity():
  3431.             return Decimal(self)
  3432.  
  3433.         # get values, pad if necessary
  3434.         torot = int(other)
  3435.         if not torot:
  3436.             return Decimal(self)
  3437.         rotdig = self._int
  3438.         topad = context.prec - len(rotdig)
  3439.         if topad:
  3440.             rotdig = '0'*topad + rotdig
  3441.  
  3442.         # let's shift!
  3443.         if torot < 0:
  3444.             rotated = rotdig[:torot]
  3445.         else:
  3446.             rotated = rotdig + '0'*torot
  3447.             rotated = rotated[-context.prec:]
  3448.  
  3449.         return _dec_from_triple(self._sign,
  3450.                                     rotated.lstrip('0') or '0', self._exp)
  3451.  
  3452.     # Support for pickling, copy, and deepcopy
  3453.     def __reduce__(self):
  3454.         return (self.__class__, (str(self),))
  3455.  
  3456.     def __copy__(self):
  3457.         if type(self) == Decimal:
  3458.             return self     # I'm immutable; therefore I am my own clone
  3459.         return self.__class__(str(self))
  3460.  
  3461.     def __deepcopy__(self, memo):
  3462.         if type(self) == Decimal:
  3463.             return self     # My components are also immutable
  3464.         return self.__class__(str(self))
  3465.  
  3466.     # PEP 3101 support.  See also _parse_format_specifier and _format_align
  3467.     def __format__(self, specifier, context=None):
  3468.         """Format a Decimal instance according to the given specifier.
  3469.  
  3470.         The specifier should be a standard format specifier, with the
  3471.         form described in PEP 3101.  Formatting types 'e', 'E', 'f',
  3472.         'F', 'g', 'G', and '%' are supported.  If the formatting type
  3473.         is omitted it defaults to 'g' or 'G', depending on the value
  3474.         of context.capitals.
  3475.  
  3476.         At this time the 'n' format specifier type (which is supposed
  3477.         to use the current locale) is not supported.
  3478.         """
  3479.  
  3480.         # Note: PEP 3101 says that if the type is not present then
  3481.         # there should be at least one digit after the decimal point.
  3482.         # We take the liberty of ignoring this requirement for
  3483.         # Decimal---it's presumably there to make sure that
  3484.         # format(float, '') behaves similarly to str(float).
  3485.         if context is None:
  3486.             context = getcontext()
  3487.  
  3488.         spec = _parse_format_specifier(specifier)
  3489.  
  3490.         # special values don't care about the type or precision...
  3491.         if self._is_special:
  3492.             return _format_align(str(self), spec)
  3493.  
  3494.         # a type of None defaults to 'g' or 'G', depending on context
  3495.         # if type is '%', adjust exponent of self accordingly
  3496.         if spec['type'] is None:
  3497.             spec['type'] = ['g', 'G'][context.capitals]
  3498.         elif spec['type'] == '%':
  3499.             self = _dec_from_triple(self._sign, self._int, self._exp+2)
  3500.  
  3501.         # round if necessary, taking rounding mode from the context
  3502.         rounding = context.rounding
  3503.         precision = spec['precision']
  3504.         if precision is not None:
  3505.             if spec['type'] in 'eE':
  3506.                 self = self._round(precision+1, rounding)
  3507.             elif spec['type'] in 'gG':
  3508.                 if len(self._int) > precision:
  3509.                     self = self._round(precision, rounding)
  3510.             elif spec['type'] in 'fF%':
  3511.                 self = self._rescale(-precision, rounding)
  3512.         # special case: zeros with a positive exponent can't be
  3513.         # represented in fixed point; rescale them to 0e0.
  3514.         elif not self and self._exp > 0 and spec['type'] in 'fF%':
  3515.             self = self._rescale(0, rounding)
  3516.  
  3517.         # figure out placement of the decimal point
  3518.         leftdigits = self._exp + len(self._int)
  3519.         if spec['type'] in 'fF%':
  3520.             dotplace = leftdigits
  3521.         elif spec['type'] in 'eE':
  3522.             if not self and precision is not None:
  3523.                 dotplace = 1 - precision
  3524.             else:
  3525.                 dotplace = 1
  3526.         elif spec['type'] in 'gG':
  3527.             if self._exp <= 0 and leftdigits > -6:
  3528.                 dotplace = leftdigits
  3529.             else:
  3530.                 dotplace = 1
  3531.  
  3532.         # figure out main part of numeric string...
  3533.         if dotplace <= 0:
  3534.             num = '0.' + '0'*(-dotplace) + self._int
  3535.         elif dotplace >= len(self._int):
  3536.             # make sure we're not padding a '0' with extra zeros on the right
  3537.             assert dotplace==len(self._int) or self._int != '0'
  3538.             num = self._int + '0'*(dotplace-len(self._int))
  3539.         else:
  3540.             num = self._int[:dotplace] + '.' + self._int[dotplace:]
  3541.  
  3542.         # ...then the trailing exponent, or trailing '%'
  3543.         if leftdigits != dotplace or spec['type'] in 'eE':
  3544.             echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
  3545.             num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
  3546.         elif spec['type'] == '%':
  3547.             num = num + '%'
  3548.  
  3549.         # add sign
  3550.         if self._sign == 1:
  3551.             num = '-' + num
  3552.         return _format_align(num, spec)
  3553.  
  3554.  
  3555. def _dec_from_triple(sign, coefficient, exponent, special=False):
  3556.     """Create a decimal instance directly, without any validation,
  3557.     normalization (e.g. removal of leading zeros) or argument
  3558.     conversion.
  3559.  
  3560.     This function is for *internal use only*.
  3561.     """
  3562.  
  3563.     self = object.__new__(Decimal)
  3564.     self._sign = sign
  3565.     self._int = coefficient
  3566.     self._exp = exponent
  3567.     self._is_special = special
  3568.  
  3569.     return self
  3570.  
  3571. # Register Decimal as a kind of Number (an abstract base class).
  3572. # However, do not register it as Real (because Decimals are not
  3573. # interoperable with floats).
  3574. _numbers.Number.register(Decimal)
  3575.  
  3576.  
  3577. ##### Context class #######################################################
  3578.  
  3579.  
  3580. # get rounding method function:
  3581. rounding_functions = [name for name in Decimal.__dict__.keys()
  3582.                                     if name.startswith('_round_')]
  3583. for name in rounding_functions:
  3584.     # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
  3585.     globalname = name[1:].upper()
  3586.     val = globals()[globalname]
  3587.     Decimal._pick_rounding_function[val] = name
  3588.  
  3589. del name, val, globalname, rounding_functions
  3590.  
  3591. class _ContextManager(object):
  3592.     """Context manager class to support localcontext().
  3593.  
  3594.       Sets a copy of the supplied context in __enter__() and restores
  3595.       the previous decimal context in __exit__()
  3596.     """
  3597.     def __init__(self, new_context):
  3598.         self.new_context = new_context.copy()
  3599.     def __enter__(self):
  3600.         self.saved_context = getcontext()
  3601.         setcontext(self.new_context)
  3602.         return self.new_context
  3603.     def __exit__(self, t, v, tb):
  3604.         setcontext(self.saved_context)
  3605.  
  3606. class Context(object):
  3607.     """Contains the context for a Decimal instance.
  3608.  
  3609.     Contains:
  3610.     prec - precision (for use in rounding, division, square roots..)
  3611.     rounding - rounding type (how you round)
  3612.     traps - If traps[exception] = 1, then the exception is
  3613.                     raised when it is caused.  Otherwise, a value is
  3614.                     substituted in.
  3615.     flags  - When an exception is caused, flags[exception] is set.
  3616.              (Whether or not the trap_enabler is set)
  3617.              Should be reset by user of Decimal instance.
  3618.     Emin -   Minimum exponent
  3619.     Emax -   Maximum exponent
  3620.     capitals -      If 1, 1*10^1 is printed as 1E+1.
  3621.                     If 0, printed as 1e1
  3622.     _clamp - If 1, change exponents if too high (Default 0)
  3623.     """
  3624.  
  3625.     def __init__(self, prec=None, rounding=None,
  3626.                  traps=None, flags=None,
  3627.                  Emin=None, Emax=None,
  3628.                  capitals=None, _clamp=0,
  3629.                  _ignored_flags=None):
  3630.         if flags is None:
  3631.             flags = []
  3632.         if _ignored_flags is None:
  3633.             _ignored_flags = []
  3634.         if not isinstance(flags, dict):
  3635.             flags = dict([(s, int(s in flags)) for s in _signals])
  3636.             del s
  3637.         if traps is not None and not isinstance(traps, dict):
  3638.             traps = dict([(s, int(s in traps)) for s in _signals])
  3639.             del s
  3640.         for name, val in locals().items():
  3641.             if val is None:
  3642.                 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
  3643.             else:
  3644.                 setattr(self, name, val)
  3645.         del self.self
  3646.  
  3647.     def __repr__(self):
  3648.         """Show the current context."""
  3649.         s = []
  3650.         s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
  3651.                  'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
  3652.                  % vars(self))
  3653.         names = [f.__name__ for f, v in self.flags.items() if v]
  3654.         s.append('flags=[' + ', '.join(names) + ']')
  3655.         names = [t.__name__ for t, v in self.traps.items() if v]
  3656.         s.append('traps=[' + ', '.join(names) + ']')
  3657.         return ', '.join(s) + ')'
  3658.  
  3659.     def clear_flags(self):
  3660.         """Reset all flags to zero"""
  3661.         for flag in self.flags:
  3662.             self.flags[flag] = 0
  3663.  
  3664.     def _shallow_copy(self):
  3665.         """Returns a shallow copy from self."""
  3666.         nc = Context(self.prec, self.rounding, self.traps,
  3667.                      self.flags, self.Emin, self.Emax,
  3668.                      self.capitals, self._clamp, self._ignored_flags)
  3669.         return nc
  3670.  
  3671.     def copy(self):
  3672.         """Returns a deep copy from self."""
  3673.         nc = Context(self.prec, self.rounding, self.traps.copy(),
  3674.                      self.flags.copy(), self.Emin, self.Emax,
  3675.                      self.capitals, self._clamp, self._ignored_flags)
  3676.         return nc
  3677.     __copy__ = copy
  3678.  
  3679.     def _raise_error(self, condition, explanation = None, *args):
  3680.         """Handles an error
  3681.  
  3682.         If the flag is in _ignored_flags, returns the default response.
  3683.         Otherwise, it sets the flag, then, if the corresponding
  3684.         trap_enabler is set, it reaises the exception.  Otherwise, it returns
  3685.         the default value after setting the flag.
  3686.         """
  3687.         error = _condition_map.get(condition, condition)
  3688.         if error in self._ignored_flags:
  3689.             # Don't touch the flag
  3690.             return error().handle(self, *args)
  3691.  
  3692.         self.flags[error] = 1
  3693.         if not self.traps[error]:
  3694.             # The errors define how to handle themselves.
  3695.             return condition().handle(self, *args)
  3696.  
  3697.         # Errors should only be risked on copies of the context
  3698.         # self._ignored_flags = []
  3699.         raise error(explanation)
  3700.  
  3701.     def _ignore_all_flags(self):
  3702.         """Ignore all flags, if they are raised"""
  3703.         return self._ignore_flags(*_signals)
  3704.  
  3705.     def _ignore_flags(self, *flags):
  3706.         """Ignore the flags, if they are raised"""
  3707.         # Do not mutate-- This way, copies of a context leave the original
  3708.         # alone.
  3709.         self._ignored_flags = (self._ignored_flags + list(flags))
  3710.         return list(flags)
  3711.  
  3712.     def _regard_flags(self, *flags):
  3713.         """Stop ignoring the flags, if they are raised"""
  3714.         if flags and isinstance(flags[0], (tuple,list)):
  3715.             flags = flags[0]
  3716.         for flag in flags:
  3717.             self._ignored_flags.remove(flag)
  3718.  
  3719.     # We inherit object.__hash__, so we must deny this explicitly
  3720.     __hash__ = None
  3721.  
  3722.     def Etiny(self):
  3723.         """Returns Etiny (= Emin - prec + 1)"""
  3724.         return int(self.Emin - self.prec + 1)
  3725.  
  3726.     def Etop(self):
  3727.         """Returns maximum exponent (= Emax - prec + 1)"""
  3728.         return int(self.Emax - self.prec + 1)
  3729.  
  3730.     def _set_rounding(self, type):
  3731.         """Sets the rounding type.
  3732.  
  3733.         Sets the rounding type, and returns the current (previous)
  3734.         rounding type.  Often used like:
  3735.  
  3736.         context = context.copy()
  3737.         # so you don't change the calling context
  3738.         # if an error occurs in the middle.
  3739.         rounding = context._set_rounding(ROUND_UP)
  3740.         val = self.__sub__(other, context=context)
  3741.         context._set_rounding(rounding)
  3742.  
  3743.         This will make it round up for that operation.
  3744.         """
  3745.         rounding = self.rounding
  3746.         self.rounding= type
  3747.         return rounding
  3748.  
  3749.     def create_decimal(self, num='0'):
  3750.         """Creates a new Decimal instance but using self as context.
  3751.  
  3752.         This method implements the to-number operation of the
  3753.         IBM Decimal specification."""
  3754.  
  3755.         if isinstance(num, basestring) and num != num.strip():
  3756.             return self._raise_error(ConversionSyntax,
  3757.                                      "no trailing or leading whitespace is "
  3758.                                      "permitted.")
  3759.  
  3760.         d = Decimal(num, context=self)
  3761.         if d._isnan() and len(d._int) > self.prec - self._clamp:
  3762.             return self._raise_error(ConversionSyntax,
  3763.                                      "diagnostic info too long in NaN")
  3764.         return d._fix(self)
  3765.  
  3766.     # Methods
  3767.     def abs(self, a):
  3768.         """Returns the absolute value of the operand.
  3769.  
  3770.         If the operand is negative, the result is the same as using the minus
  3771.         operation on the operand.  Otherwise, the result is the same as using
  3772.         the plus operation on the operand.
  3773.  
  3774.         >>> ExtendedContext.abs(Decimal('2.1'))
  3775.         Decimal('2.1')
  3776.         >>> ExtendedContext.abs(Decimal('-100'))
  3777.         Decimal('100')
  3778.         >>> ExtendedContext.abs(Decimal('101.5'))
  3779.         Decimal('101.5')
  3780.         >>> ExtendedContext.abs(Decimal('-101.5'))
  3781.         Decimal('101.5')
  3782.         """
  3783.         return a.__abs__(context=self)
  3784.  
  3785.     def add(self, a, b):
  3786.         """Return the sum of the two operands.
  3787.  
  3788.         >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
  3789.         Decimal('19.00')
  3790.         >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
  3791.         Decimal('1.02E+4')
  3792.         """
  3793.         return a.__add__(b, context=self)
  3794.  
  3795.     def _apply(self, a):
  3796.         return str(a._fix(self))
  3797.  
  3798.     def canonical(self, a):
  3799.         """Returns the same Decimal object.
  3800.  
  3801.         As we do not have different encodings for the same number, the
  3802.         received object already is in its canonical form.
  3803.  
  3804.         >>> ExtendedContext.canonical(Decimal('2.50'))
  3805.         Decimal('2.50')
  3806.         """
  3807.         return a.canonical(context=self)
  3808.  
  3809.     def compare(self, a, b):
  3810.         """Compares values numerically.
  3811.  
  3812.         If the signs of the operands differ, a value representing each operand
  3813.         ('-1' if the operand is less than zero, '0' if the operand is zero or
  3814.         negative zero, or '1' if the operand is greater than zero) is used in
  3815.         place of that operand for the comparison instead of the actual
  3816.         operand.
  3817.  
  3818.         The comparison is then effected by subtracting the second operand from
  3819.         the first and then returning a value according to the result of the
  3820.         subtraction: '-1' if the result is less than zero, '0' if the result is
  3821.         zero or negative zero, or '1' if the result is greater than zero.
  3822.  
  3823.         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
  3824.         Decimal('-1')
  3825.         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
  3826.         Decimal('0')
  3827.         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
  3828.         Decimal('0')
  3829.         >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
  3830.         Decimal('1')
  3831.         >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
  3832.         Decimal('1')
  3833.         >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
  3834.         Decimal('-1')
  3835.         """
  3836.         return a.compare(b, context=self)
  3837.  
  3838.     def compare_signal(self, a, b):
  3839.         """Compares the values of the two operands numerically.
  3840.  
  3841.         It's pretty much like compare(), but all NaNs signal, with signaling
  3842.         NaNs taking precedence over quiet NaNs.
  3843.  
  3844.         >>> c = ExtendedContext
  3845.         >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
  3846.         Decimal('-1')
  3847.         >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
  3848.         Decimal('0')
  3849.         >>> c.flags[InvalidOperation] = 0
  3850.         >>> print c.flags[InvalidOperation]
  3851.         0
  3852.         >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
  3853.         Decimal('NaN')
  3854.         >>> print c.flags[InvalidOperation]
  3855.         1
  3856.         >>> c.flags[InvalidOperation] = 0
  3857.         >>> print c.flags[InvalidOperation]
  3858.         0
  3859.         >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
  3860.         Decimal('NaN')
  3861.         >>> print c.flags[InvalidOperation]
  3862.         1
  3863.         """
  3864.         return a.compare_signal(b, context=self)
  3865.  
  3866.     def compare_total(self, a, b):
  3867.         """Compares two operands using their abstract representation.
  3868.  
  3869.         This is not like the standard compare, which use their numerical
  3870.         value. Note that a total ordering is defined for all possible abstract
  3871.         representations.
  3872.  
  3873.         >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
  3874.         Decimal('-1')
  3875.         >>> ExtendedContext.compare_total(Decimal('-127'),  Decimal('12'))
  3876.         Decimal('-1')
  3877.         >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
  3878.         Decimal('-1')
  3879.         >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
  3880.         Decimal('0')
  3881.         >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('12.300'))
  3882.         Decimal('1')
  3883.         >>> ExtendedContext.compare_total(Decimal('12.3'),  Decimal('NaN'))
  3884.         Decimal('-1')
  3885.         """
  3886.         return a.compare_total(b)
  3887.  
  3888.     def compare_total_mag(self, a, b):
  3889.         """Compares two operands using their abstract representation ignoring sign.
  3890.  
  3891.         Like compare_total, but with operand's sign ignored and assumed to be 0.
  3892.         """
  3893.         return a.compare_total_mag(b)
  3894.  
  3895.     def copy_abs(self, a):
  3896.         """Returns a copy of the operand with the sign set to 0.
  3897.  
  3898.         >>> ExtendedContext.copy_abs(Decimal('2.1'))
  3899.         Decimal('2.1')
  3900.         >>> ExtendedContext.copy_abs(Decimal('-100'))
  3901.         Decimal('100')
  3902.         """
  3903.         return a.copy_abs()
  3904.  
  3905.     def copy_decimal(self, a):
  3906.         """Returns a copy of the decimal objet.
  3907.  
  3908.         >>> ExtendedContext.copy_decimal(Decimal('2.1'))
  3909.         Decimal('2.1')
  3910.         >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
  3911.         Decimal('-1.00')
  3912.         """
  3913.         return Decimal(a)
  3914.  
  3915.     def copy_negate(self, a):
  3916.         """Returns a copy of the operand with the sign inverted.
  3917.  
  3918.         >>> ExtendedContext.copy_negate(Decimal('101.5'))
  3919.         Decimal('-101.5')
  3920.         >>> ExtendedContext.copy_negate(Decimal('-101.5'))
  3921.         Decimal('101.5')
  3922.         """
  3923.         return a.copy_negate()
  3924.  
  3925.     def copy_sign(self, a, b):
  3926.         """Copies the second operand's sign to the first one.
  3927.  
  3928.         In detail, it returns a copy of the first operand with the sign
  3929.         equal to the sign of the second operand.
  3930.  
  3931.         >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
  3932.         Decimal('1.50')
  3933.         >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
  3934.         Decimal('1.50')
  3935.         >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
  3936.         Decimal('-1.50')
  3937.         >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
  3938.         Decimal('-1.50')
  3939.         """
  3940.         return a.copy_sign(b)
  3941.  
  3942.     def divide(self, a, b):
  3943.         """Decimal division in a specified context.
  3944.  
  3945.         >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
  3946.         Decimal('0.333333333')
  3947.         >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
  3948.         Decimal('0.666666667')
  3949.         >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
  3950.         Decimal('2.5')
  3951.         >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
  3952.         Decimal('0.1')
  3953.         >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
  3954.         Decimal('1')
  3955.         >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
  3956.         Decimal('4.00')
  3957.         >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
  3958.         Decimal('1.20')
  3959.         >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
  3960.         Decimal('10')
  3961.         >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
  3962.         Decimal('1000')
  3963.         >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
  3964.         Decimal('1.20E+6')
  3965.         """
  3966.         return a.__div__(b, context=self)
  3967.  
  3968.     def divide_int(self, a, b):
  3969.         """Divides two numbers and returns the integer part of the result.
  3970.  
  3971.         >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
  3972.         Decimal('0')
  3973.         >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
  3974.         Decimal('3')
  3975.         >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
  3976.         Decimal('3')
  3977.         """
  3978.         return a.__floordiv__(b, context=self)
  3979.  
  3980.     def divmod(self, a, b):
  3981.         return a.__divmod__(b, context=self)
  3982.  
  3983.     def exp(self, a):
  3984.         """Returns e ** a.
  3985.  
  3986.         >>> c = ExtendedContext.copy()
  3987.         >>> c.Emin = -999
  3988.         >>> c.Emax = 999
  3989.         >>> c.exp(Decimal('-Infinity'))
  3990.         Decimal('0')
  3991.         >>> c.exp(Decimal('-1'))
  3992.         Decimal('0.367879441')
  3993.         >>> c.exp(Decimal('0'))
  3994.         Decimal('1')
  3995.         >>> c.exp(Decimal('1'))
  3996.         Decimal('2.71828183')
  3997.         >>> c.exp(Decimal('0.693147181'))
  3998.         Decimal('2.00000000')
  3999.         >>> c.exp(Decimal('+Infinity'))
  4000.         Decimal('Infinity')
  4001.         """
  4002.         return a.exp(context=self)
  4003.  
  4004.     def fma(self, a, b, c):
  4005.         """Returns a multiplied by b, plus c.
  4006.  
  4007.         The first two operands are multiplied together, using multiply,
  4008.         the third operand is then added to the result of that
  4009.         multiplication, using add, all with only one final rounding.
  4010.  
  4011.         >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
  4012.         Decimal('22')
  4013.         >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
  4014.         Decimal('-8')
  4015.         >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
  4016.         Decimal('1.38435736E+12')
  4017.         """
  4018.         return a.fma(b, c, context=self)
  4019.  
  4020.     def is_canonical(self, a):
  4021.         """Return True if the operand is canonical; otherwise return False.
  4022.  
  4023.         Currently, the encoding of a Decimal instance is always
  4024.         canonical, so this method returns True for any Decimal.
  4025.  
  4026.         >>> ExtendedContext.is_canonical(Decimal('2.50'))
  4027.         True
  4028.         """
  4029.         return a.is_canonical()
  4030.  
  4031.     def is_finite(self, a):
  4032.         """Return True if the operand is finite; otherwise return False.
  4033.  
  4034.         A Decimal instance is considered finite if it is neither
  4035.         infinite nor a NaN.
  4036.  
  4037.         >>> ExtendedContext.is_finite(Decimal('2.50'))
  4038.         True
  4039.         >>> ExtendedContext.is_finite(Decimal('-0.3'))
  4040.         True
  4041.         >>> ExtendedContext.is_finite(Decimal('0'))
  4042.         True
  4043.         >>> ExtendedContext.is_finite(Decimal('Inf'))
  4044.         False
  4045.         >>> ExtendedContext.is_finite(Decimal('NaN'))
  4046.         False
  4047.         """
  4048.         return a.is_finite()
  4049.  
  4050.     def is_infinite(self, a):
  4051.         """Return True if the operand is infinite; otherwise return False.
  4052.  
  4053.         >>> ExtendedContext.is_infinite(Decimal('2.50'))
  4054.         False
  4055.         >>> ExtendedContext.is_infinite(Decimal('-Inf'))
  4056.         True
  4057.         >>> ExtendedContext.is_infinite(Decimal('NaN'))
  4058.         False
  4059.         """
  4060.         return a.is_infinite()
  4061.  
  4062.     def is_nan(self, a):
  4063.         """Return True if the operand is a qNaN or sNaN;
  4064.         otherwise return False.
  4065.  
  4066.         >>> ExtendedContext.is_nan(Decimal('2.50'))
  4067.         False
  4068.         >>> ExtendedContext.is_nan(Decimal('NaN'))
  4069.         True
  4070.         >>> ExtendedContext.is_nan(Decimal('-sNaN'))
  4071.         True
  4072.         """
  4073.         return a.is_nan()
  4074.  
  4075.     def is_normal(self, a):
  4076.         """Return True if the operand is a normal number;
  4077.         otherwise return False.
  4078.  
  4079.         >>> c = ExtendedContext.copy()
  4080.         >>> c.Emin = -999
  4081.         >>> c.Emax = 999
  4082.         >>> c.is_normal(Decimal('2.50'))
  4083.         True
  4084.         >>> c.is_normal(Decimal('0.1E-999'))
  4085.         False
  4086.         >>> c.is_normal(Decimal('0.00'))
  4087.         False
  4088.         >>> c.is_normal(Decimal('-Inf'))
  4089.         False
  4090.         >>> c.is_normal(Decimal('NaN'))
  4091.         False
  4092.         """
  4093.         return a.is_normal(context=self)
  4094.  
  4095.     def is_qnan(self, a):
  4096.         """Return True if the operand is a quiet NaN; otherwise return False.
  4097.  
  4098.         >>> ExtendedContext.is_qnan(Decimal('2.50'))
  4099.         False
  4100.         >>> ExtendedContext.is_qnan(Decimal('NaN'))
  4101.         True
  4102.         >>> ExtendedContext.is_qnan(Decimal('sNaN'))
  4103.         False
  4104.         """
  4105.         return a.is_qnan()
  4106.  
  4107.     def is_signed(self, a):
  4108.         """Return True if the operand is negative; otherwise return False.
  4109.  
  4110.         >>> ExtendedContext.is_signed(Decimal('2.50'))
  4111.         False
  4112.         >>> ExtendedContext.is_signed(Decimal('-12'))
  4113.         True
  4114.         >>> ExtendedContext.is_signed(Decimal('-0'))
  4115.         True
  4116.         """
  4117.         return a.is_signed()
  4118.  
  4119.     def is_snan(self, a):
  4120.         """Return True if the operand is a signaling NaN;
  4121.         otherwise return False.
  4122.  
  4123.         >>> ExtendedContext.is_snan(Decimal('2.50'))
  4124.         False
  4125.         >>> ExtendedContext.is_snan(Decimal('NaN'))
  4126.         False
  4127.         >>> ExtendedContext.is_snan(Decimal('sNaN'))
  4128.         True
  4129.         """
  4130.         return a.is_snan()
  4131.  
  4132.     def is_subnormal(self, a):
  4133.         """Return True if the operand is subnormal; otherwise return False.
  4134.  
  4135.         >>> c = ExtendedContext.copy()
  4136.         >>> c.Emin = -999
  4137.         >>> c.Emax = 999
  4138.         >>> c.is_subnormal(Decimal('2.50'))
  4139.         False
  4140.         >>> c.is_subnormal(Decimal('0.1E-999'))
  4141.         True
  4142.         >>> c.is_subnormal(Decimal('0.00'))
  4143.         False
  4144.         >>> c.is_subnormal(Decimal('-Inf'))
  4145.         False
  4146.         >>> c.is_subnormal(Decimal('NaN'))
  4147.         False
  4148.         """
  4149.         return a.is_subnormal(context=self)
  4150.  
  4151.     def is_zero(self, a):
  4152.         """Return True if the operand is a zero; otherwise return False.
  4153.  
  4154.         >>> ExtendedContext.is_zero(Decimal('0'))
  4155.         True
  4156.         >>> ExtendedContext.is_zero(Decimal('2.50'))
  4157.         False
  4158.         >>> ExtendedContext.is_zero(Decimal('-0E+2'))
  4159.         True
  4160.         """
  4161.         return a.is_zero()
  4162.  
  4163.     def ln(self, a):
  4164.         """Returns the natural (base e) logarithm of the operand.
  4165.  
  4166.         >>> c = ExtendedContext.copy()
  4167.         >>> c.Emin = -999
  4168.         >>> c.Emax = 999
  4169.         >>> c.ln(Decimal('0'))
  4170.         Decimal('-Infinity')
  4171.         >>> c.ln(Decimal('1.000'))
  4172.         Decimal('0')
  4173.         >>> c.ln(Decimal('2.71828183'))
  4174.         Decimal('1.00000000')
  4175.         >>> c.ln(Decimal('10'))
  4176.         Decimal('2.30258509')
  4177.         >>> c.ln(Decimal('+Infinity'))
  4178.         Decimal('Infinity')
  4179.         """
  4180.         return a.ln(context=self)
  4181.  
  4182.     def log10(self, a):
  4183.         """Returns the base 10 logarithm of the operand.
  4184.  
  4185.         >>> c = ExtendedContext.copy()
  4186.         >>> c.Emin = -999
  4187.         >>> c.Emax = 999
  4188.         >>> c.log10(Decimal('0'))
  4189.         Decimal('-Infinity')
  4190.         >>> c.log10(Decimal('0.001'))
  4191.         Decimal('-3')
  4192.         >>> c.log10(Decimal('1.000'))
  4193.         Decimal('0')
  4194.         >>> c.log10(Decimal('2'))
  4195.         Decimal('0.301029996')
  4196.         >>> c.log10(Decimal('10'))
  4197.         Decimal('1')
  4198.         >>> c.log10(Decimal('70'))
  4199.         Decimal('1.84509804')
  4200.         >>> c.log10(Decimal('+Infinity'))
  4201.         Decimal('Infinity')
  4202.         """
  4203.         return a.log10(context=self)
  4204.  
  4205.     def logb(self, a):
  4206.         """ Returns the exponent of the magnitude of the operand's MSD.
  4207.  
  4208.         The result is the integer which is the exponent of the magnitude
  4209.         of the most significant digit of the operand (as though the
  4210.         operand were truncated to a single digit while maintaining the
  4211.         value of that digit and without limiting the resulting exponent).
  4212.  
  4213.         >>> ExtendedContext.logb(Decimal('250'))
  4214.         Decimal('2')
  4215.         >>> ExtendedContext.logb(Decimal('2.50'))
  4216.         Decimal('0')
  4217.         >>> ExtendedContext.logb(Decimal('0.03'))
  4218.         Decimal('-2')
  4219.         >>> ExtendedContext.logb(Decimal('0'))
  4220.         Decimal('-Infinity')
  4221.         """
  4222.         return a.logb(context=self)
  4223.  
  4224.     def logical_and(self, a, b):
  4225.         """Applies the logical operation 'and' between each operand's digits.
  4226.  
  4227.         The operands must be both logical numbers.
  4228.  
  4229.         >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
  4230.         Decimal('0')
  4231.         >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
  4232.         Decimal('0')
  4233.         >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
  4234.         Decimal('0')
  4235.         >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
  4236.         Decimal('1')
  4237.         >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
  4238.         Decimal('1000')
  4239.         >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
  4240.         Decimal('10')
  4241.         """
  4242.         return a.logical_and(b, context=self)
  4243.  
  4244.     def logical_invert(self, a):
  4245.         """Invert all the digits in the operand.
  4246.  
  4247.         The operand must be a logical number.
  4248.  
  4249.         >>> ExtendedContext.logical_invert(Decimal('0'))
  4250.         Decimal('111111111')
  4251.         >>> ExtendedContext.logical_invert(Decimal('1'))
  4252.         Decimal('111111110')
  4253.         >>> ExtendedContext.logical_invert(Decimal('111111111'))
  4254.         Decimal('0')
  4255.         >>> ExtendedContext.logical_invert(Decimal('101010101'))
  4256.         Decimal('10101010')
  4257.         """
  4258.         return a.logical_invert(context=self)
  4259.  
  4260.     def logical_or(self, a, b):
  4261.         """Applies the logical operation 'or' between each operand's digits.
  4262.  
  4263.         The operands must be both logical numbers.
  4264.  
  4265.         >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
  4266.         Decimal('0')
  4267.         >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
  4268.         Decimal('1')
  4269.         >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
  4270.         Decimal('1')
  4271.         >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
  4272.         Decimal('1')
  4273.         >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
  4274.         Decimal('1110')
  4275.         >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
  4276.         Decimal('1110')
  4277.         """
  4278.         return a.logical_or(b, context=self)
  4279.  
  4280.     def logical_xor(self, a, b):
  4281.         """Applies the logical operation 'xor' between each operand's digits.
  4282.  
  4283.         The operands must be both logical numbers.
  4284.  
  4285.         >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
  4286.         Decimal('0')
  4287.         >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
  4288.         Decimal('1')
  4289.         >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
  4290.         Decimal('1')
  4291.         >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
  4292.         Decimal('0')
  4293.         >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
  4294.         Decimal('110')
  4295.         >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
  4296.         Decimal('1101')
  4297.         """
  4298.         return a.logical_xor(b, context=self)
  4299.  
  4300.     def max(self, a,b):
  4301.         """max compares two values numerically and returns the maximum.
  4302.  
  4303.         If either operand is a NaN then the general rules apply.
  4304.         Otherwise, the operands are compared as though by the compare
  4305.         operation.  If they are numerically equal then the left-hand operand
  4306.         is chosen as the result.  Otherwise the maximum (closer to positive
  4307.         infinity) of the two operands is chosen as the result.
  4308.  
  4309.         >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
  4310.         Decimal('3')
  4311.         >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
  4312.         Decimal('3')
  4313.         >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
  4314.         Decimal('1')
  4315.         >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
  4316.         Decimal('7')
  4317.         """
  4318.         return a.max(b, context=self)
  4319.  
  4320.     def max_mag(self, a, b):
  4321.         """Compares the values numerically with their sign ignored."""
  4322.         return a.max_mag(b, context=self)
  4323.  
  4324.     def min(self, a,b):
  4325.         """min compares two values numerically and returns the minimum.
  4326.  
  4327.         If either operand is a NaN then the general rules apply.
  4328.         Otherwise, the operands are compared as though by the compare
  4329.         operation.  If they are numerically equal then the left-hand operand
  4330.         is chosen as the result.  Otherwise the minimum (closer to negative
  4331.         infinity) of the two operands is chosen as the result.
  4332.  
  4333.         >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
  4334.         Decimal('2')
  4335.         >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
  4336.         Decimal('-10')
  4337.         >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
  4338.         Decimal('1.0')
  4339.         >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
  4340.         Decimal('7')
  4341.         """
  4342.         return a.min(b, context=self)
  4343.  
  4344.     def min_mag(self, a, b):
  4345.         """Compares the values numerically with their sign ignored."""
  4346.         return a.min_mag(b, context=self)
  4347.  
  4348.     def minus(self, a):
  4349.         """Minus corresponds to unary prefix minus in Python.
  4350.  
  4351.         The operation is evaluated using the same rules as subtract; the
  4352.         operation minus(a) is calculated as subtract('0', a) where the '0'
  4353.         has the same exponent as the operand.
  4354.  
  4355.         >>> ExtendedContext.minus(Decimal('1.3'))
  4356.         Decimal('-1.3')
  4357.         >>> ExtendedContext.minus(Decimal('-1.3'))
  4358.         Decimal('1.3')
  4359.         """
  4360.         return a.__neg__(context=self)
  4361.  
  4362.     def multiply(self, a, b):
  4363.         """multiply multiplies two operands.
  4364.  
  4365.         If either operand is a special value then the general rules apply.
  4366.         Otherwise, the operands are multiplied together ('long multiplication'),
  4367.         resulting in a number which may be as long as the sum of the lengths
  4368.         of the two operands.
  4369.  
  4370.         >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
  4371.         Decimal('3.60')
  4372.         >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
  4373.         Decimal('21')
  4374.         >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
  4375.         Decimal('0.72')
  4376.         >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
  4377.         Decimal('-0.0')
  4378.         >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
  4379.         Decimal('4.28135971E+11')
  4380.         """
  4381.         return a.__mul__(b, context=self)
  4382.  
  4383.     def next_minus(self, a):
  4384.         """Returns the largest representable number smaller than a.
  4385.  
  4386.         >>> c = ExtendedContext.copy()
  4387.         >>> c.Emin = -999
  4388.         >>> c.Emax = 999
  4389.         >>> ExtendedContext.next_minus(Decimal('1'))
  4390.         Decimal('0.999999999')
  4391.         >>> c.next_minus(Decimal('1E-1007'))
  4392.         Decimal('0E-1007')
  4393.         >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
  4394.         Decimal('-1.00000004')
  4395.         >>> c.next_minus(Decimal('Infinity'))
  4396.         Decimal('9.99999999E+999')
  4397.         """
  4398.         return a.next_minus(context=self)
  4399.  
  4400.     def next_plus(self, a):
  4401.         """Returns the smallest representable number larger than a.
  4402.  
  4403.         >>> c = ExtendedContext.copy()
  4404.         >>> c.Emin = -999
  4405.         >>> c.Emax = 999
  4406.         >>> ExtendedContext.next_plus(Decimal('1'))
  4407.         Decimal('1.00000001')
  4408.         >>> c.next_plus(Decimal('-1E-1007'))
  4409.         Decimal('-0E-1007')
  4410.         >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
  4411.         Decimal('-1.00000002')
  4412.         >>> c.next_plus(Decimal('-Infinity'))
  4413.         Decimal('-9.99999999E+999')
  4414.         """
  4415.         return a.next_plus(context=self)
  4416.  
  4417.     def next_toward(self, a, b):
  4418.         """Returns the number closest to a, in direction towards b.
  4419.  
  4420.         The result is the closest representable number from the first
  4421.         operand (but not the first operand) that is in the direction
  4422.         towards the second operand, unless the operands have the same
  4423.         value.
  4424.  
  4425.         >>> c = ExtendedContext.copy()
  4426.         >>> c.Emin = -999
  4427.         >>> c.Emax = 999
  4428.         >>> c.next_toward(Decimal('1'), Decimal('2'))
  4429.         Decimal('1.00000001')
  4430.         >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
  4431.         Decimal('-0E-1007')
  4432.         >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
  4433.         Decimal('-1.00000002')
  4434.         >>> c.next_toward(Decimal('1'), Decimal('0'))
  4435.         Decimal('0.999999999')
  4436.         >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
  4437.         Decimal('0E-1007')
  4438.         >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
  4439.         Decimal('-1.00000004')
  4440.         >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
  4441.         Decimal('-0.00')
  4442.         """
  4443.         return a.next_toward(b, context=self)
  4444.  
  4445.     def normalize(self, a):
  4446.         """normalize reduces an operand to its simplest form.
  4447.  
  4448.         Essentially a plus operation with all trailing zeros removed from the
  4449.         result.
  4450.  
  4451.         >>> ExtendedContext.normalize(Decimal('2.1'))
  4452.         Decimal('2.1')
  4453.         >>> ExtendedContext.normalize(Decimal('-2.0'))
  4454.         Decimal('-2')
  4455.         >>> ExtendedContext.normalize(Decimal('1.200'))
  4456.         Decimal('1.2')
  4457.         >>> ExtendedContext.normalize(Decimal('-120'))
  4458.         Decimal('-1.2E+2')
  4459.         >>> ExtendedContext.normalize(Decimal('120.00'))
  4460.         Decimal('1.2E+2')
  4461.         >>> ExtendedContext.normalize(Decimal('0.00'))
  4462.         Decimal('0')
  4463.         """
  4464.         return a.normalize(context=self)
  4465.  
  4466.     def number_class(self, a):
  4467.         """Returns an indication of the class of the operand.
  4468.  
  4469.         The class is one of the following strings:
  4470.           -sNaN
  4471.           -NaN
  4472.           -Infinity
  4473.           -Normal
  4474.           -Subnormal
  4475.           -Zero
  4476.           +Zero
  4477.           +Subnormal
  4478.           +Normal
  4479.           +Infinity
  4480.  
  4481.         >>> c = Context(ExtendedContext)
  4482.         >>> c.Emin = -999
  4483.         >>> c.Emax = 999
  4484.         >>> c.number_class(Decimal('Infinity'))
  4485.         '+Infinity'
  4486.         >>> c.number_class(Decimal('1E-10'))
  4487.         '+Normal'
  4488.         >>> c.number_class(Decimal('2.50'))
  4489.         '+Normal'
  4490.         >>> c.number_class(Decimal('0.1E-999'))
  4491.         '+Subnormal'
  4492.         >>> c.number_class(Decimal('0'))
  4493.         '+Zero'
  4494.         >>> c.number_class(Decimal('-0'))
  4495.         '-Zero'
  4496.         >>> c.number_class(Decimal('-0.1E-999'))
  4497.         '-Subnormal'
  4498.         >>> c.number_class(Decimal('-1E-10'))
  4499.         '-Normal'
  4500.         >>> c.number_class(Decimal('-2.50'))
  4501.         '-Normal'
  4502.         >>> c.number_class(Decimal('-Infinity'))
  4503.         '-Infinity'
  4504.         >>> c.number_class(Decimal('NaN'))
  4505.         'NaN'
  4506.         >>> c.number_class(Decimal('-NaN'))
  4507.         'NaN'
  4508.         >>> c.number_class(Decimal('sNaN'))
  4509.         'sNaN'
  4510.         """
  4511.         return a.number_class(context=self)
  4512.  
  4513.     def plus(self, a):
  4514.         """Plus corresponds to unary prefix plus in Python.
  4515.  
  4516.         The operation is evaluated using the same rules as add; the
  4517.         operation plus(a) is calculated as add('0', a) where the '0'
  4518.         has the same exponent as the operand.
  4519.  
  4520.         >>> ExtendedContext.plus(Decimal('1.3'))
  4521.         Decimal('1.3')
  4522.         >>> ExtendedContext.plus(Decimal('-1.3'))
  4523.         Decimal('-1.3')
  4524.         """
  4525.         return a.__pos__(context=self)
  4526.  
  4527.     def power(self, a, b, modulo=None):
  4528.         """Raises a to the power of b, to modulo if given.
  4529.  
  4530.         With two arguments, compute a**b.  If a is negative then b
  4531.         must be integral.  The result will be inexact unless b is
  4532.         integral and the result is finite and can be expressed exactly
  4533.         in 'precision' digits.
  4534.  
  4535.         With three arguments, compute (a**b) % modulo.  For the
  4536.         three argument form, the following restrictions on the
  4537.         arguments hold:
  4538.  
  4539.          - all three arguments must be integral
  4540.          - b must be nonnegative
  4541.          - at least one of a or b must be nonzero
  4542.          - modulo must be nonzero and have at most 'precision' digits
  4543.  
  4544.         The result of pow(a, b, modulo) is identical to the result
  4545.         that would be obtained by computing (a**b) % modulo with
  4546.         unbounded precision, but is computed more efficiently.  It is
  4547.         always exact.
  4548.  
  4549.         >>> c = ExtendedContext.copy()
  4550.         >>> c.Emin = -999
  4551.         >>> c.Emax = 999
  4552.         >>> c.power(Decimal('2'), Decimal('3'))
  4553.         Decimal('8')
  4554.         >>> c.power(Decimal('-2'), Decimal('3'))
  4555.         Decimal('-8')
  4556.         >>> c.power(Decimal('2'), Decimal('-3'))
  4557.         Decimal('0.125')
  4558.         >>> c.power(Decimal('1.7'), Decimal('8'))
  4559.         Decimal('69.7575744')
  4560.         >>> c.power(Decimal('10'), Decimal('0.301029996'))
  4561.         Decimal('2.00000000')
  4562.         >>> c.power(Decimal('Infinity'), Decimal('-1'))
  4563.         Decimal('0')
  4564.         >>> c.power(Decimal('Infinity'), Decimal('0'))
  4565.         Decimal('1')
  4566.         >>> c.power(Decimal('Infinity'), Decimal('1'))
  4567.         Decimal('Infinity')
  4568.         >>> c.power(Decimal('-Infinity'), Decimal('-1'))
  4569.         Decimal('-0')
  4570.         >>> c.power(Decimal('-Infinity'), Decimal('0'))
  4571.         Decimal('1')
  4572.         >>> c.power(Decimal('-Infinity'), Decimal('1'))
  4573.         Decimal('-Infinity')
  4574.         >>> c.power(Decimal('-Infinity'), Decimal('2'))
  4575.         Decimal('Infinity')
  4576.         >>> c.power(Decimal('0'), Decimal('0'))
  4577.         Decimal('NaN')
  4578.  
  4579.         >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
  4580.         Decimal('11')
  4581.         >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
  4582.         Decimal('-11')
  4583.         >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
  4584.         Decimal('1')
  4585.         >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
  4586.         Decimal('11')
  4587.         >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
  4588.         Decimal('11729830')
  4589.         >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
  4590.         Decimal('-0')
  4591.         >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
  4592.         Decimal('1')
  4593.         """
  4594.         return a.__pow__(b, modulo, context=self)
  4595.  
  4596.     def quantize(self, a, b):
  4597.         """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
  4598.  
  4599.         The coefficient of the result is derived from that of the left-hand
  4600.         operand.  It may be rounded using the current rounding setting (if the
  4601.         exponent is being increased), multiplied by a positive power of ten (if
  4602.         the exponent is being decreased), or is unchanged (if the exponent is
  4603.         already equal to that of the right-hand operand).
  4604.  
  4605.         Unlike other operations, if the length of the coefficient after the
  4606.         quantize operation would be greater than precision then an Invalid
  4607.         operation condition is raised.  This guarantees that, unless there is
  4608.         an error condition, the exponent of the result of a quantize is always
  4609.         equal to that of the right-hand operand.
  4610.  
  4611.         Also unlike other operations, quantize will never raise Underflow, even
  4612.         if the result is subnormal and inexact.
  4613.  
  4614.         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
  4615.         Decimal('2.170')
  4616.         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
  4617.         Decimal('2.17')
  4618.         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
  4619.         Decimal('2.2')
  4620.         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
  4621.         Decimal('2')
  4622.         >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
  4623.         Decimal('0E+1')
  4624.         >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
  4625.         Decimal('-Infinity')
  4626.         >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
  4627.         Decimal('NaN')
  4628.         >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
  4629.         Decimal('-0')
  4630.         >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
  4631.         Decimal('-0E+5')
  4632.         >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
  4633.         Decimal('NaN')
  4634.         >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
  4635.         Decimal('NaN')
  4636.         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
  4637.         Decimal('217.0')
  4638.         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
  4639.         Decimal('217')
  4640.         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
  4641.         Decimal('2.2E+2')
  4642.         >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
  4643.         Decimal('2E+2')
  4644.         """
  4645.         return a.quantize(b, context=self)
  4646.  
  4647.     def radix(self):
  4648.         """Just returns 10, as this is Decimal, :)
  4649.  
  4650.         >>> ExtendedContext.radix()
  4651.         Decimal('10')
  4652.         """
  4653.         return Decimal(10)
  4654.  
  4655.     def remainder(self, a, b):
  4656.         """Returns the remainder from integer division.
  4657.  
  4658.         The result is the residue of the dividend after the operation of
  4659.         calculating integer division as described for divide-integer, rounded
  4660.         to precision digits if necessary.  The sign of the result, if
  4661.         non-zero, is the same as that of the original dividend.
  4662.  
  4663.         This operation will fail under the same conditions as integer division
  4664.         (that is, if integer division on the same two operands would fail, the
  4665.         remainder cannot be calculated).
  4666.  
  4667.         >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
  4668.         Decimal('2.1')
  4669.         >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
  4670.         Decimal('1')
  4671.         >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
  4672.         Decimal('-1')
  4673.         >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
  4674.         Decimal('0.2')
  4675.         >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
  4676.         Decimal('0.1')
  4677.         >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
  4678.         Decimal('1.0')
  4679.         """
  4680.         return a.__mod__(b, context=self)
  4681.  
  4682.     def remainder_near(self, a, b):
  4683.         """Returns to be "a - b * n", where n is the integer nearest the exact
  4684.         value of "x / b" (if two integers are equally near then the even one
  4685.         is chosen).  If the result is equal to 0 then its sign will be the
  4686.         sign of a.
  4687.  
  4688.         This operation will fail under the same conditions as integer division
  4689.         (that is, if integer division on the same two operands would fail, the
  4690.         remainder cannot be calculated).
  4691.  
  4692.         >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
  4693.         Decimal('-0.9')
  4694.         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
  4695.         Decimal('-2')
  4696.         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
  4697.         Decimal('1')
  4698.         >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
  4699.         Decimal('-1')
  4700.         >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
  4701.         Decimal('0.2')
  4702.         >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
  4703.         Decimal('0.1')
  4704.         >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
  4705.         Decimal('-0.3')
  4706.         """
  4707.         return a.remainder_near(b, context=self)
  4708.  
  4709.     def rotate(self, a, b):
  4710.         """Returns a rotated copy of a, b times.
  4711.  
  4712.         The coefficient of the result is a rotated copy of the digits in
  4713.         the coefficient of the first operand.  The number of places of
  4714.         rotation is taken from the absolute value of the second operand,
  4715.         with the rotation being to the left if the second operand is
  4716.         positive or to the right otherwise.
  4717.  
  4718.         >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
  4719.         Decimal('400000003')
  4720.         >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
  4721.         Decimal('12')
  4722.         >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
  4723.         Decimal('891234567')
  4724.         >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
  4725.         Decimal('123456789')
  4726.         >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
  4727.         Decimal('345678912')
  4728.         """
  4729.         return a.rotate(b, context=self)
  4730.  
  4731.     def same_quantum(self, a, b):
  4732.         """Returns True if the two operands have the same exponent.
  4733.  
  4734.         The result is never affected by either the sign or the coefficient of
  4735.         either operand.
  4736.  
  4737.         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
  4738.         False
  4739.         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
  4740.         True
  4741.         >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
  4742.         False
  4743.         >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
  4744.         True
  4745.         """
  4746.         return a.same_quantum(b)
  4747.  
  4748.     def scaleb (self, a, b):
  4749.         """Returns the first operand after adding the second value its exp.
  4750.  
  4751.         >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
  4752.         Decimal('0.0750')
  4753.         >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
  4754.         Decimal('7.50')
  4755.         >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
  4756.         Decimal('7.50E+3')
  4757.         """
  4758.         return a.scaleb (b, context=self)
  4759.  
  4760.     def shift(self, a, b):
  4761.         """Returns a shifted copy of a, b times.
  4762.  
  4763.         The coefficient of the result is a shifted copy of the digits
  4764.         in the coefficient of the first operand.  The number of places
  4765.         to shift is taken from the absolute value of the second operand,
  4766.         with the shift being to the left if the second operand is
  4767.         positive or to the right otherwise.  Digits shifted into the
  4768.         coefficient are zeros.
  4769.  
  4770.         >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
  4771.         Decimal('400000000')
  4772.         >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
  4773.         Decimal('0')
  4774.         >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
  4775.         Decimal('1234567')
  4776.         >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
  4777.         Decimal('123456789')
  4778.         >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
  4779.         Decimal('345678900')
  4780.         """
  4781.         return a.shift(b, context=self)
  4782.  
  4783.     def sqrt(self, a):
  4784.         """Square root of a non-negative number to context precision.
  4785.  
  4786.         If the result must be inexact, it is rounded using the round-half-even
  4787.         algorithm.
  4788.  
  4789.         >>> ExtendedContext.sqrt(Decimal('0'))
  4790.         Decimal('0')
  4791.         >>> ExtendedContext.sqrt(Decimal('-0'))
  4792.         Decimal('-0')
  4793.         >>> ExtendedContext.sqrt(Decimal('0.39'))
  4794.         Decimal('0.624499800')
  4795.         >>> ExtendedContext.sqrt(Decimal('100'))
  4796.         Decimal('10')
  4797.         >>> ExtendedContext.sqrt(Decimal('1'))
  4798.         Decimal('1')
  4799.         >>> ExtendedContext.sqrt(Decimal('1.0'))
  4800.         Decimal('1.0')
  4801.         >>> ExtendedContext.sqrt(Decimal('1.00'))
  4802.         Decimal('1.0')
  4803.         >>> ExtendedContext.sqrt(Decimal('7'))
  4804.         Decimal('2.64575131')
  4805.         >>> ExtendedContext.sqrt(Decimal('10'))
  4806.         Decimal('3.16227766')
  4807.         >>> ExtendedContext.prec
  4808.         9
  4809.         """
  4810.         return a.sqrt(context=self)
  4811.  
  4812.     def subtract(self, a, b):
  4813.         """Return the difference between the two operands.
  4814.  
  4815.         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
  4816.         Decimal('0.23')
  4817.         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
  4818.         Decimal('0.00')
  4819.         >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
  4820.         Decimal('-0.77')
  4821.         """
  4822.         return a.__sub__(b, context=self)
  4823.  
  4824.     def to_eng_string(self, a):
  4825.         """Converts a number to a string, using scientific notation.
  4826.  
  4827.         The operation is not affected by the context.
  4828.         """
  4829.         return a.to_eng_string(context=self)
  4830.  
  4831.     def to_sci_string(self, a):
  4832.         """Converts a number to a string, using scientific notation.
  4833.  
  4834.         The operation is not affected by the context.
  4835.         """
  4836.         return a.__str__(context=self)
  4837.  
  4838.     def to_integral_exact(self, a):
  4839.         """Rounds to an integer.
  4840.  
  4841.         When the operand has a negative exponent, the result is the same
  4842.         as using the quantize() operation using the given operand as the
  4843.         left-hand-operand, 1E+0 as the right-hand-operand, and the precision
  4844.         of the operand as the precision setting; Inexact and Rounded flags
  4845.         are allowed in this operation.  The rounding mode is taken from the
  4846.         context.
  4847.  
  4848.         >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
  4849.         Decimal('2')
  4850.         >>> ExtendedContext.to_integral_exact(Decimal('100'))
  4851.         Decimal('100')
  4852.         >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
  4853.         Decimal('100')
  4854.         >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
  4855.         Decimal('102')
  4856.         >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
  4857.         Decimal('-102')
  4858.         >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
  4859.         Decimal('1.0E+6')
  4860.         >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
  4861.         Decimal('7.89E+77')
  4862.         >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
  4863.         Decimal('-Infinity')
  4864.         """
  4865.         return a.to_integral_exact(context=self)
  4866.  
  4867.     def to_integral_value(self, a):
  4868.         """Rounds to an integer.
  4869.  
  4870.         When the operand has a negative exponent, the result is the same
  4871.         as using the quantize() operation using the given operand as the
  4872.         left-hand-operand, 1E+0 as the right-hand-operand, and the precision
  4873.         of the operand as the precision setting, except that no flags will
  4874.         be set.  The rounding mode is taken from the context.
  4875.  
  4876.         >>> ExtendedContext.to_integral_value(Decimal('2.1'))
  4877.         Decimal('2')
  4878.         >>> ExtendedContext.to_integral_value(Decimal('100'))
  4879.         Decimal('100')
  4880.         >>> ExtendedContext.to_integral_value(Decimal('100.0'))
  4881.         Decimal('100')
  4882.         >>> ExtendedContext.to_integral_value(Decimal('101.5'))
  4883.         Decimal('102')
  4884.         >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
  4885.         Decimal('-102')
  4886.         >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
  4887.         Decimal('1.0E+6')
  4888.         >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
  4889.         Decimal('7.89E+77')
  4890.         >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
  4891.         Decimal('-Infinity')
  4892.         """
  4893.         return a.to_integral_value(context=self)
  4894.  
  4895.     # the method name changed, but we provide also the old one, for compatibility
  4896.     to_integral = to_integral_value
  4897.  
  4898. class _WorkRep(object):
  4899.     __slots__ = ('sign','int','exp')
  4900.     # sign: 0 or 1
  4901.     # int:  int or long
  4902.     # exp:  None, int, or string
  4903.  
  4904.     def __init__(self, value=None):
  4905.         if value is None:
  4906.             self.sign = None
  4907.             self.int = 0
  4908.             self.exp = None
  4909.         elif isinstance(value, Decimal):
  4910.             self.sign = value._sign
  4911.             self.int = int(value._int)
  4912.             self.exp = value._exp
  4913.         else:
  4914.             # assert isinstance(value, tuple)
  4915.             self.sign = value[0]
  4916.             self.int = value[1]
  4917.             self.exp = value[2]
  4918.  
  4919.     def __repr__(self):
  4920.         return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
  4921.  
  4922.     __str__ = __repr__
  4923.  
  4924.  
  4925.  
  4926. def _normalize(op1, op2, prec = 0):
  4927.     """Normalizes op1, op2 to have the same exp and length of coefficient.
  4928.  
  4929.     Done during addition.
  4930.     """
  4931.     if op1.exp < op2.exp:
  4932.         tmp = op2
  4933.         other = op1
  4934.     else:
  4935.         tmp = op1
  4936.         other = op2
  4937.  
  4938.     # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
  4939.     # Then adding 10**exp to tmp has the same effect (after rounding)
  4940.     # as adding any positive quantity smaller than 10**exp; similarly
  4941.     # for subtraction.  So if other is smaller than 10**exp we replace
  4942.     # it with 10**exp.  This avoids tmp.exp - other.exp getting too large.
  4943.     tmp_len = len(str(tmp.int))
  4944.     other_len = len(str(other.int))
  4945.     exp = tmp.exp + min(-1, tmp_len - prec - 2)
  4946.     if other_len + other.exp - 1 < exp:
  4947.         other.int = 1
  4948.         other.exp = exp
  4949.  
  4950.     tmp.int *= 10 ** (tmp.exp - other.exp)
  4951.     tmp.exp = other.exp
  4952.     return op1, op2
  4953.  
  4954. ##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
  4955.  
  4956. # This function from Tim Peters was taken from here:
  4957. # http://mail.python.org/pipermail/python-list/1999-July/007758.html
  4958. # The correction being in the function definition is for speed, and
  4959. # the whole function is not resolved with math.log because of avoiding
  4960. # the use of floats.
  4961. def _nbits(n, correction = {
  4962.         '0': 4, '1': 3, '2': 2, '3': 2,
  4963.         '4': 1, '5': 1, '6': 1, '7': 1,
  4964.         '8': 0, '9': 0, 'a': 0, 'b': 0,
  4965.         'c': 0, 'd': 0, 'e': 0, 'f': 0}):
  4966.     """Number of bits in binary representation of the positive integer n,
  4967.     or 0 if n == 0.
  4968.     """
  4969.     if n < 0:
  4970.         raise ValueError("The argument to _nbits should be nonnegative.")
  4971.     hex_n = "%x" % n
  4972.     return 4*len(hex_n) - correction[hex_n[0]]
  4973.  
  4974. def _sqrt_nearest(n, a):
  4975.     """Closest integer to the square root of the positive integer n.  a is
  4976.     an initial approximation to the square root.  Any positive integer
  4977.     will do for a, but the closer a is to the square root of n the
  4978.     faster convergence will be.
  4979.  
  4980.     """
  4981.     if n <= 0 or a <= 0:
  4982.         raise ValueError("Both arguments to _sqrt_nearest should be positive.")
  4983.  
  4984.     b=0
  4985.     while a != b:
  4986.         b, a = a, a--n//a>>1
  4987.     return a
  4988.  
  4989. def _rshift_nearest(x, shift):
  4990.     """Given an integer x and a nonnegative integer shift, return closest
  4991.     integer to x / 2**shift; use round-to-even in case of a tie.
  4992.  
  4993.     """
  4994.     b, q = 1L << shift, x >> shift
  4995.     return q + (2*(x & (b-1)) + (q&1) > b)
  4996.  
  4997. def _div_nearest(a, b):
  4998.     """Closest integer to a/b, a and b positive integers; rounds to even
  4999.     in the case of a tie.
  5000.  
  5001.     """
  5002.     q, r = divmod(a, b)
  5003.     return q + (2*r + (q&1) > b)
  5004.  
  5005. def _ilog(x, M, L = 8):
  5006.     """Integer approximation to M*log(x/M), with absolute error boundable
  5007.     in terms only of x/M.
  5008.  
  5009.     Given positive integers x and M, return an integer approximation to
  5010.     M * log(x/M).  For L = 8 and 0.1 <= x/M <= 10 the difference
  5011.     between the approximation and the exact result is at most 22.  For
  5012.     L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15.  In
  5013.     both cases these are upper bounds on the error; it will usually be
  5014.     much smaller."""
  5015.  
  5016.     # The basic algorithm is the following: let log1p be the function
  5017.     # log1p(x) = log(1+x).  Then log(x/M) = log1p((x-M)/M).  We use
  5018.     # the reduction
  5019.     #
  5020.     #    log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
  5021.     #
  5022.     # repeatedly until the argument to log1p is small (< 2**-L in
  5023.     # absolute value).  For small y we can use the Taylor series
  5024.     # expansion
  5025.     #
  5026.     #    log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
  5027.     #
  5028.     # truncating at T such that y**T is small enough.  The whole
  5029.     # computation is carried out in a form of fixed-point arithmetic,
  5030.     # with a real number z being represented by an integer
  5031.     # approximation to z*M.  To avoid loss of precision, the y below
  5032.     # is actually an integer approximation to 2**R*y*M, where R is the
  5033.     # number of reductions performed so far.
  5034.  
  5035.     y = x-M
  5036.     # argument reduction; R = number of reductions performed
  5037.     R = 0
  5038.     while (R <= L and long(abs(y)) << L-R >= M or
  5039.            R > L and abs(y) >> R-L >= M):
  5040.         y = _div_nearest(long(M*y) << 1,
  5041.                          M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
  5042.         R += 1
  5043.  
  5044.     # Taylor series with T terms
  5045.     T = -int(-10*len(str(M))//(3*L))
  5046.     yshift = _rshift_nearest(y, R)
  5047.     w = _div_nearest(M, T)
  5048.     for k in xrange(T-1, 0, -1):
  5049.         w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
  5050.  
  5051.     return _div_nearest(w*y, M)
  5052.  
  5053. def _dlog10(c, e, p):
  5054.     """Given integers c, e and p with c > 0, p >= 0, compute an integer
  5055.     approximation to 10**p * log10(c*10**e), with an absolute error of
  5056.     at most 1.  Assumes that c*10**e is not exactly 1."""
  5057.  
  5058.     # increase precision by 2; compensate for this by dividing
  5059.     # final result by 100
  5060.     p += 2
  5061.  
  5062.     # write c*10**e as d*10**f with either:
  5063.     #   f >= 0 and 1 <= d <= 10, or
  5064.     #   f <= 0 and 0.1 <= d <= 1.
  5065.     # Thus for c*10**e close to 1, f = 0
  5066.     l = len(str(c))
  5067.     f = e+l - (e+l >= 1)
  5068.  
  5069.     if p > 0:
  5070.         M = 10**p
  5071.         k = e+p-f
  5072.         if k >= 0:
  5073.             c *= 10**k
  5074.         else:
  5075.             c = _div_nearest(c, 10**-k)
  5076.  
  5077.         log_d = _ilog(c, M) # error < 5 + 22 = 27
  5078.         log_10 = _log10_digits(p) # error < 1
  5079.         log_d = _div_nearest(log_d*M, log_10)
  5080.         log_tenpower = f*M # exact
  5081.     else:
  5082.         log_d = 0  # error < 2.31
  5083.         log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
  5084.  
  5085.     return _div_nearest(log_tenpower+log_d, 100)
  5086.  
  5087. def _dlog(c, e, p):
  5088.     """Given integers c, e and p with c > 0, compute an integer
  5089.     approximation to 10**p * log(c*10**e), with an absolute error of
  5090.     at most 1.  Assumes that c*10**e is not exactly 1."""
  5091.  
  5092.     # Increase precision by 2. The precision increase is compensated
  5093.     # for at the end with a division by 100.
  5094.     p += 2
  5095.  
  5096.     # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
  5097.     # or f <= 0 and 0.1 <= d <= 1.  Then we can compute 10**p * log(c*10**e)
  5098.     # as 10**p * log(d) + 10**p*f * log(10).
  5099.     l = len(str(c))
  5100.     f = e+l - (e+l >= 1)
  5101.  
  5102.     # compute approximation to 10**p*log(d), with error < 27
  5103.     if p > 0:
  5104.         k = e+p-f
  5105.         if k >= 0:
  5106.             c *= 10**k
  5107.         else:
  5108.             c = _div_nearest(c, 10**-k)  # error of <= 0.5 in c
  5109.  
  5110.         # _ilog magnifies existing error in c by a factor of at most 10
  5111.         log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
  5112.     else:
  5113.         # p <= 0: just approximate the whole thing by 0; error < 2.31
  5114.         log_d = 0
  5115.  
  5116.     # compute approximation to f*10**p*log(10), with error < 11.
  5117.     if f:
  5118.         extra = len(str(abs(f)))-1
  5119.         if p + extra >= 0:
  5120.             # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
  5121.             # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
  5122.             f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
  5123.         else:
  5124.             f_log_ten = 0
  5125.     else:
  5126.         f_log_ten = 0
  5127.  
  5128.     # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
  5129.     return _div_nearest(f_log_ten + log_d, 100)
  5130.  
  5131. class _Log10Memoize(object):
  5132.     """Class to compute, store, and allow retrieval of, digits of the
  5133.     constant log(10) = 2.302585....  This constant is needed by
  5134.     Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
  5135.     def __init__(self):
  5136.         self.digits = "23025850929940456840179914546843642076011014886"
  5137.  
  5138.     def getdigits(self, p):
  5139.         """Given an integer p >= 0, return floor(10**p)*log(10).
  5140.  
  5141.         For example, self.getdigits(3) returns 2302.
  5142.         """
  5143.         # digits are stored as a string, for quick conversion to
  5144.         # integer in the case that we've already computed enough
  5145.         # digits; the stored digits should always be correct
  5146.         # (truncated, not rounded to nearest).
  5147.         if p < 0:
  5148.             raise ValueError("p should be nonnegative")
  5149.  
  5150.         if p >= len(self.digits):
  5151.             # compute p+3, p+6, p+9, ... digits; continue until at
  5152.             # least one of the extra digits is nonzero
  5153.             extra = 3
  5154.             while True:
  5155.                 # compute p+extra digits, correct to within 1ulp
  5156.                 M = 10**(p+extra+2)
  5157.                 digits = str(_div_nearest(_ilog(10*M, M), 100))
  5158.                 if digits[-extra:] != '0'*extra:
  5159.                     break
  5160.                 extra += 3
  5161.             # keep all reliable digits so far; remove trailing zeros
  5162.             # and next nonzero digit
  5163.             self.digits = digits.rstrip('0')[:-1]
  5164.         return int(self.digits[:p+1])
  5165.  
  5166. _log10_digits = _Log10Memoize().getdigits
  5167.  
  5168. def _iexp(x, M, L=8):
  5169.     """Given integers x and M, M > 0, such that x/M is small in absolute
  5170.     value, compute an integer approximation to M*exp(x/M).  For 0 <=
  5171.     x/M <= 2.4, the absolute error in the result is bounded by 60 (and
  5172.     is usually much smaller)."""
  5173.  
  5174.     # Algorithm: to compute exp(z) for a real number z, first divide z
  5175.     # by a suitable power R of 2 so that |z/2**R| < 2**-L.  Then
  5176.     # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
  5177.     # series
  5178.     #
  5179.     #     expm1(x) = x + x**2/2! + x**3/3! + ...
  5180.     #
  5181.     # Now use the identity
  5182.     #
  5183.     #     expm1(2x) = expm1(x)*(expm1(x)+2)
  5184.     #
  5185.     # R times to compute the sequence expm1(z/2**R),
  5186.     # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
  5187.  
  5188.     # Find R such that x/2**R/M <= 2**-L
  5189.     R = _nbits((long(x)<<L)//M)
  5190.  
  5191.     # Taylor series.  (2**L)**T > M
  5192.     T = -int(-10*len(str(M))//(3*L))
  5193.     y = _div_nearest(x, T)
  5194.     Mshift = long(M)<<R
  5195.     for i in xrange(T-1, 0, -1):
  5196.         y = _div_nearest(x*(Mshift + y), Mshift * i)
  5197.  
  5198.     # Expansion
  5199.     for k in xrange(R-1, -1, -1):
  5200.         Mshift = long(M)<<(k+2)
  5201.         y = _div_nearest(y*(y+Mshift), Mshift)
  5202.  
  5203.     return M+y
  5204.  
  5205. def _dexp(c, e, p):
  5206.     """Compute an approximation to exp(c*10**e), with p decimal places of
  5207.     precision.
  5208.  
  5209.     Returns integers d, f such that:
  5210.  
  5211.       10**(p-1) <= d <= 10**p, and
  5212.       (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
  5213.  
  5214.     In other words, d*10**f is an approximation to exp(c*10**e) with p
  5215.     digits of precision, and with an error in d of at most 1.  This is
  5216.     almost, but not quite, the same as the error being < 1ulp: when d
  5217.     = 10**(p-1) the error could be up to 10 ulp."""
  5218.  
  5219.     # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
  5220.     p += 2
  5221.  
  5222.     # compute log(10) with extra precision = adjusted exponent of c*10**e
  5223.     extra = max(0, e + len(str(c)) - 1)
  5224.     q = p + extra
  5225.  
  5226.     # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
  5227.     # rounding down
  5228.     shift = e+q
  5229.     if shift >= 0:
  5230.         cshift = c*10**shift
  5231.     else:
  5232.         cshift = c//10**-shift
  5233.     quot, rem = divmod(cshift, _log10_digits(q))
  5234.  
  5235.     # reduce remainder back to original precision
  5236.     rem = _div_nearest(rem, 10**extra)
  5237.  
  5238.     # error in result of _iexp < 120;  error after division < 0.62
  5239.     return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
  5240.  
  5241. def _dpower(xc, xe, yc, ye, p):
  5242.     """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
  5243.     y = yc*10**ye, compute x**y.  Returns a pair of integers (c, e) such that:
  5244.  
  5245.       10**(p-1) <= c <= 10**p, and
  5246.       (c-1)*10**e < x**y < (c+1)*10**e
  5247.  
  5248.     in other words, c*10**e is an approximation to x**y with p digits
  5249.     of precision, and with an error in c of at most 1.  (This is
  5250.     almost, but not quite, the same as the error being < 1ulp: when c
  5251.     == 10**(p-1) we can only guarantee error < 10ulp.)
  5252.  
  5253.     We assume that: x is positive and not equal to 1, and y is nonzero.
  5254.     """
  5255.  
  5256.     # Find b such that 10**(b-1) <= |y| <= 10**b
  5257.     b = len(str(abs(yc))) + ye
  5258.  
  5259.     # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
  5260.     lxc = _dlog(xc, xe, p+b+1)
  5261.  
  5262.     # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
  5263.     shift = ye-b
  5264.     if shift >= 0:
  5265.         pc = lxc*yc*10**shift
  5266.     else:
  5267.         pc = _div_nearest(lxc*yc, 10**-shift)
  5268.  
  5269.     if pc == 0:
  5270.         # we prefer a result that isn't exactly 1; this makes it
  5271.         # easier to compute a correctly rounded result in __pow__
  5272.         if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
  5273.             coeff, exp = 10**(p-1)+1, 1-p
  5274.         else:
  5275.             coeff, exp = 10**p-1, -p
  5276.     else:
  5277.         coeff, exp = _dexp(pc, -(p+1), p+1)
  5278.         coeff = _div_nearest(coeff, 10)
  5279.         exp += 1
  5280.  
  5281.     return coeff, exp
  5282.  
  5283. def _log10_lb(c, correction = {
  5284.         '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
  5285.         '6': 23, '7': 16, '8': 10, '9': 5}):
  5286.     """Compute a lower bound for 100*log10(c) for a positive integer c."""
  5287.     if c <= 0:
  5288.         raise ValueError("The argument to _log10_lb should be nonnegative.")
  5289.     str_c = str(c)
  5290.     return 100*len(str_c) - correction[str_c[0]]
  5291.  
  5292. ##### Helper Functions ####################################################
  5293.  
  5294. def _convert_other(other, raiseit=False):
  5295.     """Convert other to Decimal.
  5296.  
  5297.     Verifies that it's ok to use in an implicit construction.
  5298.     """
  5299.     if isinstance(other, Decimal):
  5300.         return other
  5301.     if isinstance(other, (int, long)):
  5302.         return Decimal(other)
  5303.     if raiseit:
  5304.         raise TypeError("Unable to convert %s to Decimal" % other)
  5305.     return NotImplemented
  5306.  
  5307. ##### Setup Specific Contexts ############################################
  5308.  
  5309. # The default context prototype used by Context()
  5310. # Is mutable, so that new contexts can have different default values
  5311.  
  5312. DefaultContext = Context(
  5313.         prec=28, rounding=ROUND_HALF_EVEN,
  5314.         traps=[DivisionByZero, Overflow, InvalidOperation],
  5315.         flags=[],
  5316.         Emax=999999999,
  5317.         Emin=-999999999,
  5318.         capitals=1
  5319. )
  5320.  
  5321. # Pre-made alternate contexts offered by the specification
  5322. # Don't change these; the user should be able to select these
  5323. # contexts and be able to reproduce results from other implementations
  5324. # of the spec.
  5325.  
  5326. BasicContext = Context(
  5327.         prec=9, rounding=ROUND_HALF_UP,
  5328.         traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
  5329.         flags=[],
  5330. )
  5331.  
  5332. ExtendedContext = Context(
  5333.         prec=9, rounding=ROUND_HALF_EVEN,
  5334.         traps=[],
  5335.         flags=[],
  5336. )
  5337.  
  5338.  
  5339. ##### crud for parsing strings #############################################
  5340. #
  5341. # Regular expression used for parsing numeric strings.  Additional
  5342. # comments:
  5343. #
  5344. # 1. Uncomment the two '\s*' lines to allow leading and/or trailing
  5345. # whitespace.  But note that the specification disallows whitespace in
  5346. # a numeric string.
  5347. #
  5348. # 2. For finite numbers (not infinities and NaNs) the body of the
  5349. # number between the optional sign and the optional exponent must have
  5350. # at least one decimal digit, possibly after the decimal point.  The
  5351. # lookahead expression '(?=\d|\.\d)' checks this.
  5352. #
  5353. # As the flag UNICODE is not enabled here, we're explicitly avoiding any
  5354. # other meaning for \d than the numbers [0-9].
  5355.  
  5356. import re
  5357. _parser = re.compile(r"""        # A numeric string consists of:
  5358. #    \s*
  5359.     (?P<sign>[-+])?              # an optional sign, followed by either...
  5360.     (
  5361.         (?=[0-9]|\.[0-9])        # ...a number (with at least one digit)
  5362.         (?P<int>[0-9]*)          # having a (possibly empty) integer part
  5363.         (\.(?P<frac>[0-9]*))?    # followed by an optional fractional part
  5364.         (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
  5365.     |
  5366.         Inf(inity)?              # ...an infinity, or...
  5367.     |
  5368.         (?P<signal>s)?           # ...an (optionally signaling)
  5369.         NaN                      # NaN
  5370.         (?P<diag>[0-9]*)         # with (possibly empty) diagnostic info.
  5371.     )
  5372. #    \s*
  5373.     \Z
  5374. """, re.VERBOSE | re.IGNORECASE).match
  5375.  
  5376. _all_zeros = re.compile('0*$').match
  5377. _exact_half = re.compile('50*$').match
  5378.  
  5379. ##### PEP3101 support functions ##############################################
  5380. # The functions parse_format_specifier and format_align have little to do
  5381. # with the Decimal class, and could potentially be reused for other pure
  5382. # Python numeric classes that want to implement __format__
  5383. #
  5384. # A format specifier for Decimal looks like:
  5385. #
  5386. #   [[fill]align][sign][0][minimumwidth][.precision][type]
  5387. #
  5388.  
  5389. _parse_format_specifier_regex = re.compile(r"""\A
  5390. (?:
  5391.    (?P<fill>.)?
  5392.    (?P<align>[<>=^])
  5393. )?
  5394. (?P<sign>[-+ ])?
  5395. (?P<zeropad>0)?
  5396. (?P<minimumwidth>(?!0)\d+)?
  5397. (?:\.(?P<precision>0|(?!0)\d+))?
  5398. (?P<type>[eEfFgG%])?
  5399. \Z
  5400. """, re.VERBOSE)
  5401.  
  5402. del re
  5403.  
  5404. def _parse_format_specifier(format_spec):
  5405.     """Parse and validate a format specifier.
  5406.  
  5407.     Turns a standard numeric format specifier into a dict, with the
  5408.     following entries:
  5409.  
  5410.       fill: fill character to pad field to minimum width
  5411.       align: alignment type, either '<', '>', '=' or '^'
  5412.       sign: either '+', '-' or ' '
  5413.       minimumwidth: nonnegative integer giving minimum width
  5414.       precision: nonnegative integer giving precision, or None
  5415.       type: one of the characters 'eEfFgG%', or None
  5416.       unicode: either True or False (always True for Python 3.x)
  5417.  
  5418.     """
  5419.     m = _parse_format_specifier_regex.match(format_spec)
  5420.     if m is None:
  5421.         raise ValueError("Invalid format specifier: " + format_spec)
  5422.  
  5423.     # get the dictionary
  5424.     format_dict = m.groupdict()
  5425.  
  5426.     # defaults for fill and alignment
  5427.     fill = format_dict['fill']
  5428.     align = format_dict['align']
  5429.     if format_dict.pop('zeropad') is not None:
  5430.         # in the face of conflict, refuse the temptation to guess
  5431.         if fill is not None and fill != '0':
  5432.             raise ValueError("Fill character conflicts with '0'"
  5433.                              " in format specifier: " + format_spec)
  5434.         if align is not None and align != '=':
  5435.             raise ValueError("Alignment conflicts with '0' in "
  5436.                              "format specifier: " + format_spec)
  5437.         fill = '0'
  5438.         align = '='
  5439.     format_dict['fill'] = fill or ' '
  5440.     format_dict['align'] = align or '<'
  5441.  
  5442.     if format_dict['sign'] is None:
  5443.         format_dict['sign'] = '-'
  5444.  
  5445.     # turn minimumwidth and precision entries into integers.
  5446.     # minimumwidth defaults to 0; precision remains None if not given
  5447.     format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
  5448.     if format_dict['precision'] is not None:
  5449.         format_dict['precision'] = int(format_dict['precision'])
  5450.  
  5451.     # if format type is 'g' or 'G' then a precision of 0 makes little
  5452.     # sense; convert it to 1.  Same if format type is unspecified.
  5453.     if format_dict['precision'] == 0:
  5454.         if format_dict['type'] in 'gG' or format_dict['type'] is None:
  5455.             format_dict['precision'] = 1
  5456.  
  5457.     # record whether return type should be str or unicode
  5458.     format_dict['unicode'] = isinstance(format_spec, unicode)
  5459.  
  5460.     return format_dict
  5461.  
  5462. def _format_align(body, spec_dict):
  5463.     """Given an unpadded, non-aligned numeric string, add padding and
  5464.     aligment to conform with the given format specifier dictionary (as
  5465.     output from parse_format_specifier).
  5466.  
  5467.     It's assumed that if body is negative then it starts with '-'.
  5468.     Any leading sign ('-' or '+') is stripped from the body before
  5469.     applying the alignment and padding rules, and replaced in the
  5470.     appropriate position.
  5471.  
  5472.     """
  5473.     # figure out the sign; we only examine the first character, so if
  5474.     # body has leading whitespace the results may be surprising.
  5475.     if len(body) > 0 and body[0] in '-+':
  5476.         sign = body[0]
  5477.         body = body[1:]
  5478.     else:
  5479.         sign = ''
  5480.  
  5481.     if sign != '-':
  5482.         if spec_dict['sign'] in ' +':
  5483.             sign = spec_dict['sign']
  5484.         else:
  5485.             sign = ''
  5486.  
  5487.     # how much extra space do we have to play with?
  5488.     minimumwidth = spec_dict['minimumwidth']
  5489.     fill = spec_dict['fill']
  5490.     padding = fill*(max(minimumwidth - (len(sign+body)), 0))
  5491.  
  5492.     align = spec_dict['align']
  5493.     if align == '<':
  5494.         result = sign + body + padding
  5495.     elif align == '>':
  5496.         result = padding + sign + body
  5497.     elif align == '=':
  5498.         result = sign + padding + body
  5499.     else: #align == '^'
  5500.         half = len(padding)//2
  5501.         result = padding[:half] + sign + body + padding[half:]
  5502.  
  5503.     # make sure that result is unicode if necessary
  5504.     if spec_dict['unicode']:
  5505.         result = unicode(result)
  5506.  
  5507.     return result
  5508.  
  5509. ##### Useful Constants (internal use only) ################################
  5510.  
  5511. # Reusable defaults
  5512. _Infinity = Decimal('Inf')
  5513. _NegativeInfinity = Decimal('-Inf')
  5514. _NaN = Decimal('NaN')
  5515. _Zero = Decimal(0)
  5516. _One = Decimal(1)
  5517. _NegativeOne = Decimal(-1)
  5518.  
  5519. # _SignedInfinity[sign] is infinity w/ that sign
  5520. _SignedInfinity = (_Infinity, _NegativeInfinity)
  5521.  
  5522.  
  5523.  
  5524. if __name__ == '__main__':
  5525.     import doctest, sys
  5526.     doctest.testmod(sys.modules[__name__])
  5527.